useIsClient vs useIsMounted
Warning
This post is more than a year old. Information may be outdated.
Tip
useIsClient is primarily for handling SSR scenarios, while useIsMounted is for managing component lifecycle and preventing memory leaks or updates after unmounting.
Timing and Purpose
useIsClientspecifically tells you if the code is running in a browser vs server environmentuseIsMountedtells you if a component is currently mounted in the DOM
Implementation
useIsClientusesuseStatedirectly and only sets totrueonceuseIsMountedusesuseRefand returns a callback function that checks the ref
Return Value
useIsClientreturns a boolean directlyuseIsMountedreturns a function that returns a boolean
Here are scenarios where they would differ:
Server-Side Rendering
useIsClientwill befalseduring SSR and initial render, thentrueafter hydrationuseIsMountedwill betrueas soon as the component mounts, regardless of SSR
Component Lifecycle
useIsClientstaystrueonce set, even if the component unmountsuseIsMountedbecomesfalsewhen the component unmounts
Race Conditions
useIsClientis better for conditional rendering based on client/server environmentuseIsMountedis better for preventing state updates after unmounting
Backlinks1
250120Comments