Reputation: 161
I don't understand the purpose of using useState with an initializer.
Below is an example where I set a counter that persists in local storage here I have not used an arrow function to initialize it.
const [count, setCount] = useState(JSON.parse(localStorage.getItem("count")))
This example below uses an arrow function to initialize.
const [count, setCount] = useState(()=>JSON.parse(localStorage.getItem("count")))
Can someone explain when the arrow function would be used and for what purpose.
Upvotes: 1
Views: 634
Reputation: 53874
Like stated in docs:
The
initialState
argument is the state used during the initial render. In subsequent renders, it is disregarded. If the initial state is the result of an expensive computation, you may provide a function instead, which will be executed only on the initial render.
So, on passing a value, on every render the value will be calculated.
// Will call JSON.parse and get item "count" from local storage
// on **every** render
const [count, setCount] = useState(JSON.parse(localStorage.getItem("count")))
Passing a callback will called only once.
// Will call JSON.parse and get item "count" from local storage
// **once** on initial render
const [count, setCount] = useState(()=>JSON.parse(localStorage.getItem("count")))
In the next example, having a value calc()
(similar to the first case) as the initial state will log "called" on every render. While having a callback, won't.
const calc = () => {
console.log("called");
return 42;
};
const App = () => {
// value: calc()
// const [state, setState] = useState(calc());
// callback : () => calc()
const [state, setState] = useState(calc);
return (
<>
{state}
<button onClick={() => setState(p => p + 1)}>render</button>
</>
);
};
Upvotes: 2