React ~ Hooks ~ useState - rohit120582sharma/Documentation GitHub Wiki

Perhaps the most critical part of React is the ability for individual components to own and manage their own state.

Namely, useState allows you to add some local state to function components. It can preserve values between function calls/renders and trigger a re-render of the component.

The only argument to useState is the initial state and it returns a pair: the current state value and a function that lets you update it. It’s similar to this.setState in a class, except it doesn’t merge the old and new state together.

With useState, whenever you’re setting the current state based on the previous state, you’ll want to pass a function to your updater function so you get the correct, most up to date value.

import React from 'react';

function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = React.useState(0);

    const increment = () => {
        setCount(count + 1);
    }
    const doubleIncrement = () => {
        setCount((prevCount) => prevCount + 2);
    }

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={increment}>Click me</button>
            <button onClick={doubleIncrement}>Click me to add count+2</button>
        </div>
    );
}
⚠️ **GitHub.com Fallback** ⚠️