To persist the value of useState
in localStorage
and load it on page load, we can use the useEffect
hook. In this example, we will create a basic counter that will increment its value on each click and persist its value in localStorage
.
Here's the code:
555 chars26 lines
In the above code, we are using the useState
hook to create a state variable count
, which is initially set by reading its value from localStorage
. We are parsing the value returned from localStorage
as an integer using parseInt()
.
We are using the useEffect
hook to persist the value of count
in localStorage
on every update. We are passing an array with count
as its only element to the useEffect
hook, which makes sure that the localStorage
is updated only when the count
value changes.
Finally, we have an incrementCount
function that updates the value of count
by calling the setCount
function. On every update, the value of count
is displayed on the screen, and we have provided a Save to LocalStorage
option to store the count value in localStorage
.
gistlibby LogSnag