From the course: Build Modern Web Apps with React, Hooks, State Management, and APIs Using Vite or Next.js

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

Lazy initialization

Lazy initialization

Welcome back. In this video, we'll discuss the lazy initialization approach when we have an expensive state setup. Let me define the problem for you first. Consider that we are defining a UState hook and the initial value for that UState hook is going to come from an expensive function. By expensive it means that this is going to be including multiple computations and based on that computation that initial value can be calculated. You can think of any complex formula or an API call that actually fetches your initial state value. In some cases this might be possible too or you have to run some computations at your machine learning level, and then you have to set that state value. It can be anything, but the point to understand is that this is an expensive operation. Here is an example that will define it, that for example, we have a compute expensive value function and we can say that, okay, this function is going to do some computations and the initial value of our state is going to…

Contents