Subscribe for Free Tips, Tutorials, and Special Discounts
We're in this together!
We respect your privacy. Unsubscribe at any time.
Question: Do hooks "run" on a NextJS server?
Answer: Yes and no. State hooks, like useState
and useReducer
will get their initial data. But there is no re-rendering flow on a server so you should never try to use the state setter function from a useState
or the dispatch
from a useReducer
. When you change the state of a useState
or useReducer
it doesn't happen immediately, you need a re-render cycle to see the new data. That doesn't happen on the server, so you will only see the initial state.
useMemo
and useCallback
are synchronous on the server and run just fine.
useEffect
and useLayoutEffect
don't run on the server at all. They only run on the client which is why some folks use them to detect when client components are mounted on the client.
useRef
, like useState
and useReducer
will have it's initial value. If you assign a ref to an HTML tag that will not happen on the server because the server has no DOM to attach the reference to.
You could conceivably set the current
of a useRef
but that updated value would be cleared on the next request, so it doesn't make much sense to do that. Attempting to do that would mean that you would want some kind of persistent state on the server, which is an anti-pattern. Servers should be stateless.
Share this article with your friends
Written by Jack Herrington
Jack Herrington is a Full Stack Principal Engineer who orchestrated the rollout of React/NextJS at Walmart Labs and Nike. He is also the "Blue Collar Coder" on YouTube where he posts weekly videos on advanced use of React and NextJS as well as other frontend technologies trends. His YouTube channel hosts an entire free courses on React and TypeScript. He has written seven books including most recently No-BS TypeScript which is a companion book to the YouTube course.