Last updated: Apr 6, 2024
Reading time·2 min

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.
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.

We used the useState hook to
initialize our state variable and get access to its setState method.
const [count, setCount] = useState(0);
onClick handler to a button element, but it doesn't necessarily have to be a button.<button onClick={handleClick}>Increment</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.
const handleClick = event => { setCount(count + 1); };
You can update the component's state in your handleClick function.
Here is an example that sets the onClick handler on the h2 element.
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 onClick={handleClick}>Count: {count}</h2> </div> ); }; export default App;

If you need to get notified every time a state variable changes, you can add it to the dependencies array of the useEffect hook as we did in the example.
useEffect(() => { console.log('Count is now: ', count); }, [count]);
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 rerun.
I've also written an article on how to update the state when props change.
If you want to calculate the next state based on the current state, pass a
function to your setState() method.
import {useEffect, useState} from 'react'; const App = () => { const [count, setCount] = useState(0); useEffect(() => { console.log('Count is now: ', count); }, [count]); const handleClick = event => { // 👇️ Calculate the next state based on the 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.