setState()

what is state?

State is a built-in object that is used to contain data or information about a component. A component’s state can change over time. Whenever it changes, the component re-renders. The change in state can happen as a response to user action or system-generated events and these changes determines the behaviour of the component and how it will render.

To allow you to make updates to your React applications, you make a call to a function named setState(). setState performs a shallow merge between the new state and the previous state. This action triggers a re-render of the component and its descendants.

  • A state can be modified based on user action or network changes
  • Every time the state of an object changes, React re-renders the component to the browser
  • The state object is initialised in the constructor
  • The state object can store multiple properties
  • this.setState() is used to change the value of the state object
  • setState() function performs a shallow merge between the new and the previous state

parameters

  • updater This can be an object with a number of key-value pairs that should be merged into the state or a function that returns such an object.
  • callback (optional) A function that will be executed after setState() has been executed successfully. Due to the fact that calls to setState() are not guaranteed by React to be atomic, this can sometimes be useful if you want to perform some action after you are positive that setState() has been executed successfully.