Friday, May 8, 2020

useState Hook example in React 16.8

In the previous post we saw that the useState Hook is used to define state props in a function component, in this post we shall see a small example on how the useState hook works in action.

In this post we will create a function component and define a state prop count using the useState hook, we will attach a function setCount which will be used to change the value of the count prop. We will also attach the setCount function to the click event handler of a button, so that each time the button is clicked the setCount function will be called which will increase the value of the count state prop by 1.

import React, { useState } from 'react';
import './App.css';

function UseStateComponent() {
    const [count, setCount] = useState(0);
 
    return (
    <div className="App">
        <header className="App-header">
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
            Click me
            </button>
        </header>
    </div>
    );
}

export default UseStateComponent;

Build and run the application, initially the count value will be displayed as 0, each time we click the button the value of the count increases by 1 and displays the incremented value as follows.






Search Flipkart Products:
Flipkart.com

No comments: