React Fundamentals

0% completed

Previous
Next
Derived State

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,

  • completedTasks is derived dynamically using the .filter() method.
  • It filters the tasks array, returning only the tasks where 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.

Why Avoid Storing Derived State?

Storing derived state directly in your component can lead to issues such as:

  1. Inconsistencies: If the original state or props change, the derived state might not update correctly, causing bugs.
  2. Redundant Updates: Maintaining multiple sources of truth increases the complexity of keeping everything in sync.
  3. Unnecessary Complexity: Calculating derived state on the fly is often simpler and reduces code bloat.

When Should You Use Derived State?

Derived state is best suited for scenarios like:

  • Filtering a list of items based on user input.
  • Calculating totals, averages, or other aggregate data.
  • Displaying conditional content based on props or state.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next