I am new to react Hooks! Am trying to make use of useState in my code. While I was using it I found a term \"Lazy initial state\"
https://reactjs.org
The argument passed to useState
is the initialState
, the value which initializes your state in the first render and is disregarded in subsequent renders. But imagine the following situation
const Component = () =>{
const [state, setState] = useState(getInitialHundredItems())
}
Imagine this being called on each render without need (remember even though the initial value is disregarded upon next renders, the function which initializes it still gets called).
For use cases like this instead of just provide a value you can pass a function
which returns the initial state, this function will only be executed once (initial render) and not on each render like the above code will
const Component = () =>{
const [state, setState] = useState(() => getInitialHundredItems())
}