DEV Community

Hihi
Hihi

Posted on

Lazy Initialization in React

I read about lazy init lately when enrolled in FrontendMaster course from Brian Holt. It is said that lazy init is used when you want to perform some heavy calculation actions rather than primitive values in the useState hook. For example calculating some complex formula, creating some DOM elements,...

const [currentDOM, setCurrentDOM] 
  = useState(React.createElement('div'))
Enter fullscreen mode Exit fullscreen mode

Keep in mind that useState's value is init-ed only once when the component is loaded up, after that it will behave naturally with its inner state. So, with the heavy actions or results of complex calculation, we would like to calculate - or init them once until further next changes to save some performance by not re-calculating these costly actions. This can be improve by using Lazy Initialization: passing the return value in a callback function

const [currentDOM, setCurrentDOM] 
  = useState(() => React.createElement('div'))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)