React setState

A Guide to Understanding Tricky React setState in Simple Terms

December 1, 2022
Umar Elbelel
React.js

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Introduction

Let us take that one doesn’t have a database setup on their React project and wants user interactivity. React offers out-of-the-box functionality to save temporary memory, just like RAM within your project, with React setState.

This tutorial will take us on how, when, and where to set up this temporary memory(state) to effectively utilize the SPA (Single Page Application) functionality.

Before starting, check out CopyCat if you are looking for some cool react tools to help speed up your development, . Copycat helps developers by converting the UI design to usable React components.

What is this setState in React?

To understand setState() in react, we need first to understand what a state is. A state is the most complex thing in React, and it’s something both beginners and experienced developers need help understanding.

The state object is where you store property values that belong to the component. One of the significant features is that it allows the change of the user’s output in response to the user’s inputs. It also affects how a component renders or behaves.

React components with a state are referred to as stateful components, while those that do not have states are stateless components. A component can have an initial state set, access it, and update it.

Now that we know what state is in react, we can continue to discuss what setState has to do with React. The setState() is a function that allows you to initiate and modify a component’s state in a React class component.

How does setState function in React?

Now that we know the “what,” let’s get to the “How.” Think of setState() as a request rather than an immediate command to update the component. React may delay it for better-perceived performance and then update several components in a single pass. In the rare case that you need to force the DOM update to be applied synchronously, you may wrap it in flushSync, which may hurt performance.

SetState also queues changes within the component state and initiates a re-render on the component and its children with the updated state. It is also the primary method to update the user interface in response to event handlers and server responses. It allows a callback function that runs after setting the state.

The code snippet below shows how to implement the setState() method.

import React, { Component } from 'react'

class Test extends Component {
  constructor(props) {
    super(props)

    state = {
      search: ''
    }
  }
}

The code above shows a class component with the constructor where the state is declared. The state will have predefined properties, in this case, the search variable.

Note: The setSate() can only be used within a class component.

To properly demonstrate the implementation of setState, we will take a simple example of a counter. It will increment and decrement at the click of a button. The code snippets below show the example.

import React, { Component } from 'react'

class Test extends Component {

constructor(props) {
    super(props)

    state = {
      count: 0
    }
  }

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 })
}

handleDecrement = () => {
  this.setState({ count: this.state.count - 1 })
}
  render() {
    return (
      <div>
        <div>
          {this.state.count}
        </div>
        <button onClick={this.handleIncrement}>Increment by 1</button>
        <button onClick={this.handleDecrement}>Decrement by 1</button>
      </div>
    )
  }
}

To use setState, as said earlier, we have to declare the variable we want in the state object; we then use the setState method to change the value or state of the variable declared within the state object.

To access the properties of the state, we use this.state.count, which allows the display of the value within the render method.

Next is to be able to change the state. To do that, we called this.setState({count:1}), which accesses the properties of the state and allows us to set a new value to the properties.

There are some key rules to note when using setState()

  1. Do not modify State directly.//wrong this.state.count = 1This means that you cannot use this.state to update or assign a value to a state. You must use the setState() to modify a state.//Correct this.setState({ count: 1 })
  2. Do not depend on this.state immediately after calling setState() and use the callback function instead.

How do you use setState callback in React?

The callback function in useState allows us to run a function after the state is set. The below code snippets elaborate more on it.

ApiCall= () => {
  // API Call
}
handleIncrement = () => {
  this.setState({ count: this.state.count + 1 },this.ApiCall)
}

In the code above, we initialize a new function ApiCall(), which we invoke within the setState() as a second parameter. This allows for the ApiCall() to be called after setting the state.

What to use instead of setState in React?

When discussing setState(), we mentioned that it is used within a class component, so when using a functional component, accessing a state, or setting a state, we use one of the react hooks, the useState().

It gives you the same feeling as the setState() within the functional components.

The code snippet below shows the use of useState().

import React, { useEffect, useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  
  return(
    //code
  )
}

The code above shows us how to setState with the useState() method.

The useState() accepts an initial state and returns two values:

  • The current state.
  • A function that updates the state.

Notice that we are destructuring the returned values from useState().

The first value, count, is our current state.

The second value, setCount, is the function used to update our state.

Note: These names are variables that can be named anything you want.

Lastly, we set the initial state to an empty string: useState(“”)

We can call the current State within the return method to read the state.

return(
    <div>
    <p>{count}</p>
    </div>
  )

To update the state, we invoke the second value, the function that will update the state.

handleIncrement = () => {
  setCount(count + 1)
}

The code above sets the count state.

The useState hooks do not have a callback function; instead, we can use another react hook, the useEffect(), which takes in a second argument, an array of dependencies.

import React, { useEffect, useState } from 'react';

function App() {
  const [count, setCount] = useState(0);
  
useEffect(()=>{

},[dependencies])

  return(
    //code
  )
}

We can then pass the count state as a dependency, which allows the useEffect() to be called whenever the count state is changed.

The code snippet below shows how to implement an API call when the count state is changed.

import React, { useEffect, useState } from 'react';

function App() {
  const [count, setCount] = useState(0);

handleIncrement = () => {
  setCount(count + 1)
}

useEffect(()=>{
// API CALL
},[count])

  return(
    <div>
    <p>{count}</p>
      <button onClick={handleIncrement}>Increment by 1</button>
    </div>
  )
}

Frequently Asked Questions

Does setState take a callback?

As discussed earlier, setState takes an optional callback function executed once setState is completed and the component is rendered. We will show a code snippet subsequently on how to add a callback function to the setState method.

The setState() does not always immediately update the component. It may batch or defer the update until later, which makes reading this.state right after calling setState() a potential pitfall. Instead, use the setState callback (), which is guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

The first argument is an updater function with the signature:

(state, props) => stateChange

SetState() will always lead to a re-render unless shouldComponentUpdate() returns false. If mutable objects are being used and conditional rendering logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

Can we have a callback function that will be invoked when setState has finished?

The callback function will be called when a function’s status is modified. This callback function only exists within a class component.

The example below shows how to implement a callback function.

The code snippet below explains.

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 },callback function)
}

Using the increment function, let’s say we want to make a call to an API to change and update the database.

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 },this.apiCall)
}

apiCall = ()=>{
  // API CALL
}

Can we setState in the render method React?

Class components use the render function. The ReactDOM.render() function takes two arguments, HTML code, and an HTML element.

The render() function should also be pure, meaning it should not modify a component’s state. Setting or using setState() allows the component to create infinite loops. The render() functions do not affect the component’s state.

It also returns the same results for every invoked operation without direct interaction with the browser. In this case, avoid the use of setState within the render method.

Some of the purposes of the render function are listed below,

  • The purpose of the function is to display the specified HTML code inside the specified HTML element.
  • In the render() method, we can read props and state and return our JSX code to the root component of our app.
  • In the render() method, we cannot change the state, and we cannot cause side effects( such as making an HTTP request to the webserver).

Conclusion

SetState is an important method within a React component. It is one of the reasons we have the SPA. This tutorial demonstrates what and how setState is used with a class and functional component. For more resources on setState checkout, the React documentation and the links to some awesome youtube videos on React setState.

Interesting Reads From Our Blogs

Lastly, check out our incredible tool, CopyCat, which helps you perfect the art of copying code. CopyCat converts your Figma designs to Bootstrap code in no time.

Happy Coding!

Related Articles

  • React.js

    How to Add Toast Notifications to a React App Using React Toastify

    Introduction to Toast Notifications Notifications are ways to keep a user aware of the success or failure of their activity on a website and if not done correctly, the user may find your website overly uninteresting or have an unpleasant…

    October 14, 2022
  • React.js

    A Beginner’s Guide to React’s useEffect Hook

    Introduction React's version 16.8+ is packed with several hooks with robust functionalities-including the React useEffect Hook. These hooks, over time, have allowed developers to write even more expressive and readable code by providing a more straightforward API to handle React…

    August 13, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code