Do Hooks "Run" On A NextJS Server?
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.