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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay