When I was exploring the world of frontend with React, I heard that you shouldn't call functions in useState. I was not aware for a long time how bad this advice was. It's useful to know when calling functions in useState makes sense and what benefits it can bring.
Let's assume that in an example application, the initial state depends on calculations that we can consider expensive to call.
const expensiveFilterFunction = (data: Data) => {
// return result of expensive function
}
Assigning the result from the function to a variable inside the component, will cause the function to be called again each time it is rendered.
function ExampleComponent({data}: Data) {
const initialFilteredData = expensiveFilterFunction(data)
const [state, setState] = useState(initialFilteredData)
return (
// UI
)
}
Remember that we only need the initial state during the first rendering of the component. Every subsequent function call in the example will be redundant.
When making optimizations in the component, we should change the way the state is initialized.
function ExampleComponent({data}: Data) {
const [state, setState] = useState(() => expensiveFilterFunction(data))
return (
// UI
)
}
This way of initializing the state is called lazy initialization, and it avoids unnecessarily performing costly operations every time the component is re-rendered.
Go back to Articles