Member-only story

Function as initial state of useState hook — Benefits

Vinodh Thangavel
1 min readJul 3, 2023

--

Initial state argument of useState can be of any type including function.

useState(initialState)

If you pass a function as initialState, it will be treated as an initializer function.

It should be pure, should take no arguments, and should return a value of any type. React will call your initializer function when initializing the component, and store its return value as the initial state

function getInitialState(){
....
return something
}

const [content, setContent] = useState(getInitialState()) - // Inefficient

useState will use its argument only on initial render, so any value passed as argument on subsequent renders will be ignored, but getInitialState function will be executed unnecessarily as its return is not used by useState on next renders.

This can be wasteful if it’s creating large arrays or performing expensive calculations.

function getInitialState(){
....
return something
}

const [content, setContent] = useState(getInitialState) // Efficent way

Now we are passing the handler reference of the function instead of calling it and sending its return value, useState will call this function only once when the initial render happens.

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet