React State

Dushani Ranasinghe
4 min readAug 15, 2024

--

When building interactive UIs with React, managing data and ensuring that the UI updates correctly is crucial. One of the fundamental concepts that enable this functionality is state. In this article, we will explore what state is, how it works, and why it’s essential in React development.

What is State in React?

State in React refers to an object that holds data or information about a component. This data can change over time, and it plays a vital role in controlling how the component behaves and renders. Unlike props, which are passed to the component from its parent, state is managed within the component itself.

To get a better understanding of state, let’s use a real-world example.

A Real-World Example: Shopping Cart

Imagine you’re building a shopping cart for an online store. The shopping cart needs to keep track of the items a user wants to purchase.

Here’s how state would be used in this scenario:

  1. Initial State: You start with an empty cart, initializing the state with an empty array to hold items.
  2. Adding Items: When a user adds an item to the cart, you update the state to include the new item. Once the state is updated, the cart component re-renders to show the updated list of items.
  3. Removing Items: When a user removes an item, you update the state to exclude that item. After it’s removed, the component re-renders to reflect the changes.

Let’s see how this works in code:

import React, { useState } from 'react';

function ShoppingCart() {
// Initialize state with an empty array
const [cart, setCart] = useState([]);

// Function to add an item to the cart
const addItem = (item) => {
setCart([...cart, item]);
};

// Function to remove an item from the cart
const removeItem = (item) => {
setCart(cart.filter(cartItem => cartItem !== item));
};

return (
<div>
<h1>Shopping Cart</h1>
<ul>
{cart.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<button onClick={() => addItem('Apple')}>Add Apple</button>
<button onClick={() => addItem('Banana')}>Add Banana</button>
<button onClick={() => removeItem('Apple')}>Remove Apple</button>
</div>
);
}

export default ShoppingCart;

How State Updates and Re-Renders Work

  • Initial Render: The cart is empty, so the list is empty.
  • Add Apple: Clicking “Add Apple” calls addItem('Apple'), updating the state to ['Apple']. The component re-renders to show "Apple" in the list.
  • Add Banana: Clicking “Add Banana” calls addItem('Banana'), updating the state to ['Apple', 'Banana']. The component re-renders to show both items.
  • Remove Apple: Clicking “Remove Apple” calls removeItem('Apple'), updating the state to ['Banana']. The component re-renders to show only "Banana."

React uses a virtual DOM to efficiently update only the parts of the UI that need to change when the state is updated. This ensures smooth and performant user experiences, even as the application grows in complexity.

Best Practices for Managing State

Managing state effectively is key to building robust and maintainable React applications. Here are a few best practices to keep in mind:

  • Avoid Direct Mutations: Always use setter functions like setState to update state, rather than modifying it directly. This ensures that React can properly track changes and trigger re-renders.
  • Keep State Minimal: Only store data in state that directly impacts the rendering of the component. Derived or computed data should be kept outside of state to avoid unnecessary re-renders.
  • Structure State Thoughtfully: As your application grows, think about how to structure your state to avoid unnecessary complexity. Consider breaking down state into smaller, manageable parts.

Scaling State Management

As our shopping cart example grows, we might need to store more complex data, such as the quantity of each item or the total price. React state can manage this, but as the complexity increases, it might be beneficial to explore more advanced state management solutions like Redux or Context API.

Key Points about State:

  • Dynamic Data: State allows components to manage and respond to dynamic data, such as user inputs, API responses, or changes in the component’s internal state.
  • Local to Component: Each component can have its own state, independent of other components. This encapsulation helps in building modular and reusable components.
  • Reactivity: When the state of a component changes, React automatically re-renders the component to reflect the new state.

Understanding state is the first step toward mastering React’s powerful UI capabilities. By effectively managing state, we can build dynamic and responsive applications.

--

--

Dushani Ranasinghe
Dushani Ranasinghe

Written by Dushani Ranasinghe

Undergraduate - University of Moratuwa Faculty of IT

No responses yet