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.
is useEffect()
covers life cycle methods like ComponentWillRecevieProps()
or static getDerivedStateFromProps()
and how use them without classes ?
Hi Mostafa,
Checkout the docs on useEffect
:)
So if a use a function as argument to useState it is called just on the fisrt render ?! that's interesting!
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?
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.