Table of Contents
Practical example: Traffic lights
Another example: Shopping list
Immer Hooks
Counter {count.value}
Summarize
Home Web Front-end CSS Tutorial Using Immer for React State Management

Using Immer for React State Management

Apr 18, 2025 am 10:41 AM

Using Immer for React State Management

React applications rely on status to track application data. The status changes with user interaction. When the state changes, we need to update the state displayed by the user interface, which is usually implemented using React's setState method.

Since React's state is immutable (can't be modified directly), when the state becomes complex, updating the state becomes very tricky and difficult to understand and maintain.

This is where Immer comes into play. This article will explore how to simplify React state management using Immer. Immer uses the concept of "draft" (draft), which you can understand as a copy of the state, not the state itself. You can imagine Immer performing a copy operation on the state and then modifying it in a safe place without affecting the original state. All updates are made on draft, and only the changed parts in draft will be updated to the actual state.

For example, your application status is as follows:

 this.state = {
  name: 'Kunle',
  age: 30,
  city: 'Lagos',
  country: 'Nigeria'
}
Copy after login

If the user celebrates his 31st birthday, we need to update the value of age . Using Immer, a state copy (draft) is created.

Imagine that this copy is handed over to a messenger, who handed over the copy to Kunle. There are now two replicas: the current state and the draft replica handed to Kunle. Kunle modified age in draft to 31. The messenger then returns the modified draft to the app, the app compares the two versions, and only updates age , because this is the only part of the draft that has changed.

This method does not break the principle of immutable states, because the current state will not be modified directly. Immer simplifies management of immutable states.

Practical example: Traffic lights

Let's build a simple traffic light application with Immer.

Using Immer, the component code is as follows:

 const {produce} = immer;

class App extends React.Component {
  state = {
    red: 'red', 
    yellow: 'black', 
    green: 'black',
    next: "yellow"
  };

  componentDidMount() {
    this.interval = setInterval(() => this.changeHandle(), 3000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  handleRedLight = () => {
    this.setState(
      produce(draft => {
        draft.red = 'red';
        draft.yellow = 'black';
        draft.green = 'black';
        draft.next = 'yellow';
      })
    );
  };

  handleYellowLight = () => {
    this.setState(
      produce(draft => {
        draft.red = 'black';
        draft.yellow = 'yellow';
        draft.green = 'black';
        draft.next = 'green';
      })
    );
  };

  handleGreenLight = () => {
    this.setState(
      produce(draft => {
        draft.red = 'black';
        draft.yellow = 'black';
        draft.green = 'green';
        draft.next = 'red';
      })
    );
  };

  changeHandle = () => {
    if (this.state.next === 'yellow') {
      this.handleYellowLight();
    } else if (this.state.next === 'green') {
      this.handleGreenLight();
    } else {
      this.handleRedLight();
    }
  };

  render() {
    Return (
      <div classname="box">
        <div classname="circle" style="{{backgroundColor:" this.state.red></div>
        <div classname="circle" style="{{backgroundColor:" this.state.yellow></div>
        <div classname="circle" style="{{backgroundColor:" this.state.green></div>
      </div>
    );
  }
}
Copy after login

produce is the default function provided by Immer. We pass this as a parameter to setState method. produce function receives a function that accepts draft as an argument. Inside this function, we can modify draft copy.

A simpler way to write:

 const handleLight = (state) => {
  return produce(state, (draft) => {
    draft.red = 'black';
    draft.yellow = 'black';
    draft.green = 'green';
    draft.next = 'red';
  });
};

// Use in components:
handleGreenLight = () => {
  const nextState = handleLight(this.state);
  this.setState(nextState);
};
Copy after login

We pass the current state and the function that accepts draft as arguments to the produce function.

Another example: Shopping list

If you have used React for a while, you should be familiar with the spread operator. Using Immer, especially when dealing with array state, you don't need to use extension operators.

Let's create a shopping list app to illustrate this further.

Component code:

 class App extends React.Component {
  // ... (constructor and other methods) ...

  handleSubmit = (e) => {
    e.preventDefault();
    const newItem = {
      id: uuid.v4(),
      name: this.state.name,
      price: this.state.price
    };
    this.setState(
      produce(draft => {
        draft.list = draft.list.concat(newItem);
      })
    );
  };

  // ... (render method) ...
}
Copy after login

When adding a new product, we need to update the list status. Use setState and extension operators:

 handleSubmit = (e) => {
  // ...
  this.setState({ list: [...this.state.list, newItem] });
};
Copy after login

Using extension operators can become very complicated if multiple states need to be updated. Using Immer, this becomes very simple.

What if we want to call the callback function after the state is updated? For example, we want to calculate the total price of the item in the list.

 handleSubmit = (e) => {
  // ...
  this.setState(
    produce(draft => {
      draft.list = draft.list.concat(newItem);
    }), () => {
      this.calculateAmount(this.state.list);
    }
  );
};

calculateAmount = (list) => {
  let total = 0;
  list.forEach(item => total = item.price);
  this.setState(
    produce(draft => {
      draft.totalAmount = total;
    })
  );
};
Copy after login

The callback function is called after the status is updated and the updated status is used.

Immer Hooks

use-immer is a hook that allows you to manage state in a React application. Let's demonstrate with a simple counter example:

 import React from "react";
import {useImmer} from "use-immer";

const Counter = () => {
  const [count, updateCounter] = useImmer({ value: 0 });

  function increment() {
    updateCounter(draft => {
      draft.value ;
    });
  }

  Return (
    <div>
      <h1 id="Counter-count-value">Counter {count.value}</h1>
      <button onclick="{increment}">Increment</button>
    </div>
  );
};

export default Counter;
Copy after login

useImmer is similar to useState . It returns the status and an update function. When the component is loaded, the status value is the same as the value passed to useImmer . Using the returned update function, we can create an increment function to increase the counter value.

Immer also provides a hook similar to useReducer : useImmerReducer .

Summarize

You can start using Immer in your next project, or gradually apply it to your current project. It simplifies React state management. Code examples can be found on GitHub. (Please provide a GitHub link if it exists)

The above is the detailed content of Using Immer for React State Management. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;s out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles