Store Values in localStorage with the React useEffect Hook

Share this video with your friends

Send Tweet

When you refresh the page in JavaScript, it will clear values that you possibly want to be persisted if you don't store it somewhere as in localStorage.

Storing something in localStorage is a side effect and in React 16.6 you can utilize useEffect to deal with exactly this type of situation. In this lesson, we'll use useEffect to set a state variable in state whenever state is updated.

We'll also look at some optimizations available to us with useEffect so we don't have it running every time the component renders.

Mostafa Hesham
Mostafa Hesham
~ 6 years ago

is useEffect() covers life cycle methods like ComponentWillRecevieProps()or static getDerivedStateFromProps() and how use them without classes ?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

Hi Mostafa,

Checkout the docs on useEffect :)

Oroneki
Oroneki
~ 6 years ago

So if a use a function as argument to useState it is called just on the fisrt render ?! that's interesting!

meyastrolabs
meyastrolabs
~ 6 years ago

Not only useEffect() has side effect, even useState() is not pure as it access / mutable value outside the function. I my opinion, Hooks doesn't encapsulate the side effects boundary clearly. What do you think?

meyastrolabs
meyastrolabs
~ 6 years ago

When we render more than one counter, then react maintains 2 separate counters in state, but localStorage has only one count reference. I doesn't matter as it is only an example.