How To Update State Of A Component In ReactJS

In this article will learn how to update state of a component in reactJS.

–First of all, create react project.

1). Update the state of functional Components:

-In the function-based component, we can update the state using usestate. 

-first, we need to create a function-based component in our file and import usestate from react.

import React, { useState } from 'react';

-we declare the state variable name count and it’s set to 0.

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

-we can update the count state using setCount.

-add the below code to change the value of the count.

import React, { useState } from 'react';

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

    const addHandler = () =>{
        setCount(count + 1)
    }
    return <>
         <h3>Function Component : {count}</h3>
        <button onClick={addHandler}>+</button>
    </>;
}

export default App;

output:

 

2). Update the state of Class-Based Components: 

-First, we need to create a class-based component.

-In class components, we can initialize state in two ways:

1.In  a constructor function

2.In class property

-add the below code to change the value of the count.

import React, { Component } from 'react';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        }
    }
    
    render() {
        const addHandler = () => {
            this.setState({
                count: this.state.count + 1
            })
        }
        return (
            <div>
                <h3>Class Component : {this.state.count}</h3>
                <button onClick={addHandler}>+</button>
            </div>
        );
    }
}

export default App;

output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories