reactjsnext.jsuse-effecthydrationpre-rendering

why does the useEffect hook even with no dependecies still "run" on the client side even though the page has been pre-rendered by next-js


I thought that the pre-rendering process would mean that hooks like useEffect will already be executed on the server.

I read something about hydration, don't know if it explains this occurrence but couldn't understand it clearly from the blogs that explained the term.


Solution

  • Pre-rendering on the server side means the conversion of your react codes into a minimal HTML representation of your UI, it doesn't mean your component is mounting(i.e. elements are created and inserted into the DOM) or updating after initial mounting/rendering. Pre-rendering is specific to NextJS as in Server Side Rendering/Static Page Generation. useEffect runs at least once after the initial render and here render means either the mount or the update after the initial mount of the component whereas the server doesn't mount obviously and hence useEffect doesn't run on the server.

    As for hydration, it is simply the process whereby the pre-rendered/static page is converted into a dynamic/interactive page when loaded by browser as it runs client side javascripts like attachment of event listeners for instance.