SoFunction
Updated on 2025-04-13

Definition, use and correct use of State in React component

Preface

In React application development,stateis a key concept used by components to store and manage data. It allows components to display different UIs according to different states. This article will introduce in detailstateThe definition, usage and how to update correctlystate, help developers better understand and apply this core feature.

1.1 state and its features

State is similar to props, but state is private and completely controlled by the current component

Don't modify the state directly: the constructor is the only one that can be givenPlace to assign.

State updates may be asynchronous: for performance reasons, React may put multiplesetState()Merge the calls into one call.

State update will be merged: when you callsetState()When React will merge the objects you provide to the current state

1.2 Definition and use of state

Currently, there are two ways to use the state in react:

1.2.1 Classes of es6 - Constructors

src/

import React from 'react'
import ReactDOM  from 'react-dom/client'
​
// When introduced, the suffix name can be omitted and can be configured in webpack// import App from './01-App-parent-child'
// import App from './02-App-parent-child-value'
// import App from './03-App-parent-child-value-default'
// import App from './04-App-parent-child-value-default-type'
// import App from './05-App-props-children'
// import App from './06-App-mutiple-props-children'
// import App from './07-App-mouse-tracker'
// import App from './08-App-render-props'
import App from './09-App-state-es6'
​
const root = (('root'))
​
(<App />)

src/

import React, { Component } from 'react';
​
/**
  * ES6 stipulates that subclasses must call super() in constructor() method, otherwise an error will be reported.
 This is because the subclass's own this object must be shaped first through the constructor of the parent class.
 Get the same instance properties and methods as the parent class, and then process them and add the subclass's own instance properties and methods.
 If the super() method is not called, the subclass will not get its own this object.
 ​
  The inheritance mechanism of ES5 is to create an independent subclass instance object first.
  Then add the parent class method to this object, that is, "Instance is in front, inheritance is in back".
  The inheritance mechanism of ES6 is to first add the properties and methods of the parent class to an empty object.
  Then use the object as an instance of the subclass, that is, "Inheritance first, instance later"
  */
class App extends Component {
  // es6's class - constructor  constructor (props) {
    super(props) // Call the constructor(props) of the parent class     = { // Add the subclass's own instance attributes and methods, and state is used as the initialization state attribute in react      date: new Date()
    }
  }
  render() {
    return (
      <div>
        The time is now:{ ()  + () }
      </div>
    );
  }
}
​
export default App;

1.2.2 es7's class - attribute initializer

src/

import React from 'react'
import ReactDOM  from 'react-dom/client'
​
// When introduced, the suffix name can be omitted and can be configured in webpack// import App from './01-App-parent-child'
// import App from './02-App-parent-child-value'
// import App from './03-App-parent-child-value-default'
// import App from './04-App-parent-child-value-default-type'
// import App from './05-App-props-children'
// import App from './06-App-mutiple-props-children'
// import App from './07-App-mouse-tracker'
// import App from './08-App-render-props'
// import App from './09-App-state-es6'
import App from './10-App-state-es7'
​
const root = (('root'))
​
(<App />)

src/

import React, { Component } from 'react';
​
// Recommended writing methodclass App extends Component {
  state = { // Attributes of class es7    date: new Date()
  }
  render() {
    return (
      <div>
        The time is now:{ ()  + () }!!!
      </div>
    );
  }
}
​
export default App;

1.3 How to modify the state correctly

setState()Queue changes to component state and notify React that it needs to re-render the component and its subcomponents using the updated state. This is the main way to update the user interface in response to event processors and process server data.

WillsetState()A command that is considered a request rather than an immediate update of the component. For better perceived performance, React delays calling it and then updates multiple components by passing it at once.

setState()Components are not always updated immediately. It will batch postpone updates. This makes it in the callsetState()Read immediately afterIt has become a hidden danger. To eliminate hidden dangers, please usecomponentDidUpdateorsetStatecallback function (setState(updater, callback)), both methods can be guaranteed to be triggered after the application is updated.

Remember the three principles of modifying the status:

Do not modify the State directly

state = { a: 10 }
 = 100 // ❌

Updates to state may be asynchronous

state = { a: 10 }
({a:  + 1 })
({a:  + 1 })
({a:  + 1 })
() // 10

Updates to state will be merged

1.4 () Methods and Features

setState()Will be a componentstateThe object is scheduled to be updated once. When state changes, the component will be re-rendered.

setState()Two parameters can be added,

setState()The second parameter of the optional callback function, which will be insetStateAfter the merging and re-rendering component is completed, execute

1.4.1 Transfer functions

Parameter 1 is a formal parameterupdaterfunction:

((state, props) => stateChange[, callback] )

src/

import React from 'react'
import ReactDOM  from 'react-dom/client'
​
// When introduced, the suffix name can be omitted and can be configured in webpack// import App from './01-App-parent-child'
// import App from './02-App-parent-child-value'
// import App from './03-App-parent-child-value-default'
// import App from './04-App-parent-child-value-default-type'
// import App from './05-App-props-children'
// import App from './06-App-mutiple-props-children'
// import App from './07-App-mouse-tracker'
// import App from './08-App-render-props'
// import App from './09-App-state-es6'
// import App from './10-App-state-es7'
import App from './11-App-setState-function'
​
const root = (('root'))
​
(<App />)

src/

import React, { Component } from 'react';
​
class App extends Component {
  state = {
    count: 100
  }
  render() {
    return (
      <div>
        {  }
        <button onClick={ () => {
          ((state, props) => {
            (state, props)
            return {
              count:  + 1
            }
          })
          ((state, props) => {
            (state, props)
            return {
              count:  + 1
            }
          })
          ((state, props) => {
            (state, props)
            return {
              count:  + 1
            }
          })
        } }>add</button>
      </div>
    );
  }
}
​
export default App

The received in the updater functionstateandpropsAll guaranteed to be up-to-date. The return value of updater will be asstatePerform shallow merge.

1.4.2 Passing objects

src/

import React from 'react'
import ReactDOM  from 'react-dom/client'
​
// When introduced, the suffix name can be omitted and can be configured in webpack// import App from './01-App-parent-child'
// import App from './02-App-parent-child-value'
// import App from './03-App-parent-child-value-default'
// import App from './04-App-parent-child-value-default-type'
// import App from './05-App-props-children'
// import App from './06-App-mutiple-props-children'
// import App from './07-App-mouse-tracker'
// import App from './08-App-render-props'
// import App from './09-App-state-es6'
// import App from './10-App-state-es7'
// import App from './11-App-setState-function'
import App from './12-App-setState-object'
​
const root = (('root'))
​
(<App />)

src/

import React, { Component } from 'react';
// Why?// const obj = { a: 100 }
// Object merge in es6// const newObj = (obj, {a: 100 + 1}, {a: 100 + 1}, {a: 100 + 1})
// (newObj) // { a: 101 }
​
class App extends Component {
  state = {
    count: 10
  }
  render() {
    return (
      <div>
        {  }
        <button onClick={ () => {
          ({
            count:  + 1
          })
          ({
            count:  + 1
          })
          ({
            count:  + 1
          })
          ()
        } }>add</button>
      </div>
    );
  }
}
​
export default App;

This form ofsetState()is asynchronous and will be multiple in the same cyclesetStateBatch processing is equivalent to

(
prevState,
{count:  + 1},
{count:  + 1},
...
)

Called afterwardsetState()Called first within the same periodsetState, so the number of items is only increased once. If the subsequent state depends on the current state, it is recommended to use the form of the updater function instead (it has been implemented in the previous case). Or continue in the second parameter.

src/

import React from 'react'
import ReactDOM  from 'react-dom/client'
​
// When introduced, the suffix name can be omitted and can be configured in webpack// import App from './01-App-parent-child'
// import App from './02-App-parent-child-value'
// import App from './03-App-parent-child-value-default'
// import App from './04-App-parent-child-value-default-type'
// import App from './05-App-props-children'
// import App from './06-App-mutiple-props-children'
// import App from './07-App-mouse-tracker'
// import App from './08-App-render-props'
// import App from './09-App-state-es6'
// import App from './10-App-state-es7'
// import App from './11-App-setState-function'
// import App from './12-App-setState-object'
import App from './13-App-setState-callback'
​
const root = (('root'))
​
(<App />)

src/

import React, { Component } from 'react';
​
​
class App extends Component {
  state = {
    count: 10
  }
  render() {
    return (
      <div>
        {  }
        <button onClick={ () => {
          ({
            count:  + 1
          }, () => {
            ({
              count:  + 1
            }, () => {
              ({
                count:  + 1
              })
            })
          })
          () // 10
        } }>add</button>
      </div>
    );
  }
}
​
export default App;

Questions to think about:

1.When and why is setState() executed in batches?

2.Why not update directly?

Summarize

Through the introduction of this article, we understandstateImportance in React components and how to define and use them in ES6 and ES7 class componentsstate. At the same time, we also discussed the correct updatestateMethods including usingsetState()Things to note when doing the method. Following these best practices can help us avoid common pitfalls and improve the performance and reliability of our applications.

This is the article about the definition, use and correct update methods of State in React components. For more information about React State components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!