0% completed
Derived state refers to a value that is computed based on existing state or props. Instead of storing this value directly in the component's state, it is calculated dynamically as needed. This approach helps you avoid duplicating data and ensures your application stays consistent.
For example, if you have a list of products and you want to display only the items on sale, the list of sale items can be derived from the main product list instead of storing it separately in the state.
Example:
Let’s consider a scenario where you have a list of tasks, and you want to display only the tasks marked as completed.
import React, { useState } from "react"; function TaskList() { const [tasks, setTasks] = useState([ { id: 1, name: "Learn React", completed: true }, { id: 2, name: "Build a project", completed: false }, { id: 3, name: "Read documentation", completed: true }, ]); // Derived state: Filter completed tasks const completedTasks = tasks.filter(task => task.completed); return ( <div> <h1>Completed Tasks</h1> <ul> {completedTasks.map(task => ( <li key={task.id}>{task.name}</li> ))} </ul> </div> ); } export default TaskList;
In this example,
task.completed
evaluates to true.There’s no need to store completedTasks in the state because it’s calculated based on tasks.
We have successfully derived state (completedTasks) from the existing tasks
state.
Storing derived state directly in your component can lead to issues such as:
Derived state is best suited for scenarios like:
.....
.....
.....