Derived State in React

Aldy Kusuma

I Putu Aldy Cahyakusuma

Software Engineer

1 min read min read

Jan 05, 2025

State management is a fundamental aspect of React development, playing a crucial role in the performance and maintainability of applications. Among the various challenges in state management, derived state is a concept that is often misunderstood. This guide aims to demystify derived state, highlight best practices, identify common pitfalls, and provide practical solutions with code examples.

What is Derived State?

Derived state is any value that can be computed from existing state or props within your React components. Instead of storing these computed values in separate state variables, they should be calculated dynamically as needed. This approach reduces the amount of state, ensures consistency, and minimizes the risk of errors.

Why Use Derived State?

Derived state is useful because it allows you to compute values on-the-fly based on the current state or props, ensuring that your UI is always in sync with the underlying data. This can lead to more efficient rendering and a cleaner codebase, as you avoid unnecessary state variables that need to be kept in sync.

When Not to Use Derived State

Avoid using derived state when the computation is expensive and needs to be performed frequently, as this can negatively impact performance. In such cases, consider memoizing the computed value or using a state management library that supports derived state caching.

Pitfalls of Storing Derived State

Storing derived state can introduce several problems:

  1. Redundancy: Storing values that can be computed from existing state leads to unnecessary duplication.
  2. Inconsistency: If the base state changes without updating the derived state, it can cause bugs and unpredictable behavior.
  3. Increased Complexity: Additional state variables complicate your component logic.

A Common Mistake to Avoid

Consider a scenario where you have a list of items and need to display the count of these items. A typical mistake is storing the count in the state, which can lead to the aforementioned issues. Here's an example of what to avoid: