This is the second day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

Hi, today we’re going to talk about the React concept of functional programming: immutable data.

If you read the title, don’t worry, you might be worried that you need some knowledge of functional programming, not at all, today we’re going to talk about the basics of what is immutable data? What are the benefits of this approach with React?

example

React takes the immutable data nature of functional programming.

Immutable in React means that state is always the same value.

Do not modify state directly. If you encounter an array or object, use a copy to make changes.

Here’s a simple example:

Basic types of

Wrong to do:

this.state.count++
this.setState({
    count:this.state.count
})
Copy the code

What you should do:

this.setState({
    count:this.state.count + 1
})
Copy the code

Reference types

Wrong to do:


this.state.obj1.a = 100
this.state.obj2.a = 100
this.setState({
    obj1: this.state.obj1,
    obj2: this.state.obj2
})
Copy the code

What you should do:

this.setState({
    obj1: Object.assign({}, this.state.obj1, {a: 100}),
    obj2: {... this.state.obj2,a: 100}})Copy the code

The advantages of functional programming with immutable values

Let’s talk about the benefits of immutable values in functional programming.

Reduce bugs

If we define a variable as const, if you want to change the variable, you need to copy it out. This way, you can make your code far less buggy.

Generate simple state management for easy maintenance

This is because state in a program is very difficult to maintain, especially in the case of concurrency. Think about it: If your code has a complex state, it’s easy to get bugs when someone changes it later.

Immutable values in React using functional programming

Let’s look at functional programming in React

Performance optimization

In the life cycle shouldComponentUpdate, React will compare the old and new states. If the state is directly modified to be used in the calculation of other variables, but in fact the state does not need to be modified, it will lead to weird updates and unnecessary updates, so it is very clever to use this way. And it’s very efficient.

Can track the modification trace, easy to troubleshoot

Using this.setState to modify the state value is equivalent to opening an opening to change the value, and all modifications will take such an opening. Compared with direct modification, this kind of control is stronger, and can effectively record and track the changes of each state, which is very helpful for bug detection.

At the end

Let me know in the comments section if you have any opinions or thoughts about React and functional programming.