Updating state in Functional Component

Using React useState hook to access and modify the state in the functional component

Syntax to update state in functional component:

setState((prev) => prev + 1);

Updating state to re-render in Functional Component Example:

Updating state in the functional component using the React JS hooks.

Javascript




// Filename - App.js
 
import { useState } from "react";
 
function App() {
    const [counter, setCounter] = useState(0);
 
    const handleIncrease = () => {
        setCounter((prev) => prev + 1);
    };
 
    const handleDecrease = () => {
        setCounter((prev) => prev - 1);
    };
 
    console.log("Rendering!!!");
 
    return (
        <div
            style={{ textAlign: "center", margin: "auto" }}
        >
            <h1 style={{ color: "green" }}>
                w3wiki
            </h1>
            <h3>
                React exmaple for updating state to
                re-render in functional component
            </h3>
            <button onClick={handleDecrease}>
                decrease
            </button>
            <span style={{ margin: "10px" }}>
                {counter}
            </span>
            <button onClick={handleIncrease}>
                increase
            </button>
        </div>
    );
}
 
export default App;


Output: Open the browser and go to http://localhost:3000, you will see the following output.

How to update state to re-render the component in ReactJS ?

In React, when the state is updated it initiates to re-render the component and its child components to update the new data on the UI of the application.

Similar Reads

Prerequisites

React Functional Components React Class Components React Hooks...

Update state to re-render the component in React:

There are different ways in the functional and class components to update a state to re-render the component in React JS....

1. Updating state in Functional Component

Using React useState hook to access and modify the state in the functional component...

2. Updating state in Class Component

...