Update a component's state on Click in React

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Update a component's state on Click in React #

To update a component's state on click, add an onClick prop to an element and set it to a function. The function will be invoked every time the element is clicked, which allows us to update the component's state on click.

App.js
import {useEffect, useState} from 'react'; const App = () => { const [count, setCount] = useState(0); useEffect(() => { console.log('Count is now: ', count); }, [count]); const handleClick = event => { setCount(count + 1); }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); }; export default App;

Every time the user clicks on the button, the count state variable gets updated.

update state on click

We used the useState hook to initialize our state variable and get access to its setState method.

We added an onClick handler to a button element, but it doesn't necessarily have to be a button.

You can set the onClick prop on different types of elements and every time the element is clicked, the handleClick function will get invoked.

You can update the component's state in your handleClick function.

If you need to get notified every time a state variable changes, you can add it to the dependencies array of the useEffect hook like we did in the example.

The second parameter we passed to the useEffect hook is an array of dependencies. The function we passed to the hook will get invoked any time one of the dependencies changes.

We added the count state variable to the hook's dependencies array, so any time count changes, the logic in our useEffect hook will re-run.

If you want to calculate the next state based on the current state, pass a function to your setState() method.

App.js
import {useEffect, useState} from 'react'; const App = () => { const [count, setCount] = useState(0); useEffect(() => { console.log('Count is now: ', count); }, [count]); const handleClick = event => { // 👇️ calculate next state based on current state setCount(prevCount => prevCount + 1); }; return ( <div> <h2>Count: {count}</h2> <button onClick={handleClick}>Increment</button> </div> ); }; export default App;

The function we passed to setCount is guaranteed to be invoked with the current (most up to date) state. This should be your preferred approach to update a component's state based on its current state.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.