Recently I came across a strange behavior in an application that uses Next.js. I noticed the issue was caused during a routing redirect using router.push
inside a useEffect
hook. Between troubleshooting and testing the code between the server and client side, I put console.log
s to quickly check the state of data. While doing so I discovered the following:
The useEffect
or Effect hook doesn’t work on the server side in Next.js. This is because the useEffect
is used to run code after React has updated the DOM. The server side only returns a generated HTML to the client. Then, React on the client side is in charge of hydrating the HTML, making this the first time React updates the DOM in applications using SSR.
If you don’t know or remember what the term hydrate is, it is the process of rendering server-side HTML content and attempting to attach any event listeners (onClick
, onSubmit
, etc) detected in the existing markup.