React.js

ReactJS setState Example

ReactJS has grown in popularity and is one of the most used frameworks. In this article, we look at the setState method of ReactJS. With earlier versions of React state feature was limited to components implemented using ES6 classes. But now with the introduction of hooks even function components can have state. We look at both the cases and how we should modify state by using the setState function and its different variants.

For the purpose of this article I will create a simple React application using the create-react-app package from the ReactJS team. The tools and frameworks used to implement this example are as follows. Some are mandatory whilst others may be replaced with your favorites.

1. Initial Setup

We get started by running the below command. This creates the initial structure and configuration of our example application.

>npx create-react-app my-app .

Once this command completes our application must be ready. The folder structure should resemble the below screen shot:

ReactJS setState - Application Structure
Application Structure

2. State in Class Component

Let us create our first component named ClickCounter in a file named the same. We use the ES6 class construct to build our component. This component renders a couple of buttons and a span. On click of one of the buttons a counter is updated and the count is displayed in the span. On click of the other button we reset the counter back to zero.

The code for our component looks like below. We store the counter in state which is internal to the component. On click we update the state using the version of setState that takes a callback and passes it the previous state and props as parameters.

ClickCounter.js

import React from 'react';

class ClickCounter extends React.Component {
    constructor(props) {
        super(props);
        this.state = { count: 0 };
    }
    render() {
        return <>
            <span>Button clicked {this.state.count} times!
                </span>
            <button onClick={this.handleClick}>Click Me</button>
            <button onClick={this.resetCounter}>
                 Reset Counter</button>
        </>;
    }
    resetCounter = () => {
        this.setState({ count: 0 });
    }
    handleClick = () => {
        this.setState((state, props) => 
            ({ count: state.count + 1 }));
    }
}
export default ClickCounter;

As you can see we have used the callback version of setState in the handleClick event handler. We use the value of the counter in the previous state to create a new state. This leads to an update of our component and it is re rendered. Similarly in the reset button’s click handler we use the version of setState to reset the counter back to zero. Next let us implement the same using function components and hooks.

3. State in Function Components

Now let us implement the component we wrote above as function component. We create a separate file named ClickComponentFunc.js for this component. To enable using state with this component we additionally import the useState hook from react. We use it as follows to create a property count in state:

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

And that’s how we can use state in a function component. The count variable can be used to access the state property and setCount can be used to set the value of the count property. The complete code for our function component looks like below

ClickComponentFunc.js

import React, { useState } from "react";

export default function ClickCounterFunc(props) {

    const [count, setCounter] = useState(0);
    const updateCounter = () => {
        setCounter(count + 1);
    };
    const resetCounter = () => {
        setCounter(0);
    };
    return <>
        <span>Button clicked {count} times!</span>
        <button onClick={updateCounter}>Click Me!</button>
        <button onClick={resetCounter}>Reset Counter</button>
    </>;

}

In the next section we run our application and see the results.

4. Running the Application

To run the application and see the results we run the following command at the root of our application

>npm start

This command starts our application and opens it in the default browser at the url http://localhost:3000. The result looks like below

Project Output

5. Download the Source Code

Download
You can download the full source code of this example here: ReactJS setState Example

Siddharth Seth

Siddharth is a Software Development Professional with a Master degree in Computer Applications from IGNOU. He has over 14 years of experience. And currently focused on Software Architecture, Cloud Computing, JavaScript Frameworks for Client and Server, Business Intelligence.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button