[NextJS Tip] Why do we have to write "use client" when using hooks?

October 11, 2024

If you've worked with Next.js, you've probably come across the advice to add use client; when using React hooks like useState, useEffect, or usePathname in your components.

But do you know why?

These hooks depend on the browser API and "reactivity" — the mechanism that re-renders components when their state changes.

In React, "reactivity" refers to how components re-render when their state or props change. This behavior is only available in the client-side environment, where the browser API and DOM exist.

On the server, there’s no browser context — no window object, no access to the DOM — so hooks like usePathname() simply can't function.

So, whenever you're working with hooks in Next.js, remember that "use client" ensures your components run in the right environment.