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.

Advanced scenario 2: Derived state

Advanced scenario 2: Derived state

Welcome back. In this video, we are going to do the advanced scenario number 2 that is the derived state scenario. In this scenario, we have to compute a state value inside the parent and only need to pass on the result to children. By compute, I mean that the state is declared inside the parent component as well as there is some calculation that is happening on the state inside the parent component as well. The child components are different and they just need to show the exact updated calculated value. That way we avoid recalculation inside the child components and the calculation step is kept inside the parent component as well. This way, we keep our logic centralized and performant. There is the example that we are going to follow. We are going to have a cart parent component. This component will have the items that the cart is going to have. We are going to simulate that using an array. And we need to do the total items calculation along with its price. So the fields as you can…

Contents