Back to all questions
The use-local-storage hook returns the real value only after mounting. Is it a bug?
Last updated
How use-local-storage hook works
By default, the use-local-storage hook
retrieves the value from local storage in useEffect only after the component is mounted.
It is implemented this way to avoid hydration mismatches if the value is used in the
output markup of the component.
Example:
valueduring server-side rendering:dark(default value)valueat initial render:dark(default value)valueafter mounting:lightordarkdepending on the value in local storage (value from local storage)
Reading value in first render
If your application does not have server-side rendering or you do not use the
value in the output markup of the component, you can read the value from local storage
in the first render. To do that, set the getInitialValueInEffect: false option:
Example:
valueduring server-side rendering:dark(default value)valueat initial render:lightordarkdepending on the value in local storage (value from local storage)valueat subsequent renders:lightordarkdepending on the value in local storage (value from local storage)