Persistent State in React
Posted on 26th May 2020
3 min read•
Sometimes we need to preserve the state in a React app in cases where we close the browser or reload the page. In this guide I’ll show you a simple custom hook to store the state in
First create a function called
useStickyState with the initial state (
initialState) as an argument.
Then let’s initialize the state and return it and the function to change it.
Next we’ll add an effect to store the state in
localstorage when the state changes. Since we need an key to store a value in local storage we’ll add one as an argument.
In its current form the state will always initialize with
initialState, but we need to load the state from
localstorage if available. We can use lazy initialization to check
localstorage and use it’s value if present. If not, use
To finish up the hook, let’s add and return a function to remove clear up the value in
Below is an example on how to use the
useStickyState hook to save the value in an
If you enjoyed this post please leave a like or two below!!!
Check out my latest post...Making delayed network requests in React after state changes
13th September 2021