About this Post

React useState hook example.


We're going to create a simple counter with React Hooks. We'll use the useState hook to manage the state of the counter.

Current count: 0

Let's dive in! There are three (3) main controls to our counter:

  • A button to increment our initial count
  • A button to decrement our count value
  • A button to reset our count back to the initialCount

Notes:

  • For a11y purposes, we've also given our button elements some aria-label definitions.
  • We'll initialize the counter to 0 using the component's initialCount prop.
  • Our counter example doesn't have any checks in place to prevent the count from going below 0, but you likely may want to add some checks to prevent that from happening.

Here' the React code for our simple counter:

// src/components/Counter.jsx import { useState } from 'react'; export function Counter({ initialCount = 0 }) { // count is the current value of the counter // setCount is the function that updates the counter const [count, countUpdate] = useState(initialCount); return ( <div> <p> Current count: <span class="count-value">{count}</span> </p> <button aria-label="Reset our counter value" onClick={() => countUpdate(initialCount)} > Reset </button> <button aria-label="Decrease the counter value" onClick={() => countUpdate((prevCount) => prevCount - 1)} > - </button> <button aria-label="Increment the counter value" onClick={() => countUpdate((prevCount) => prevCount + 1)} > + </button> </div> ); }

If we want to introduce more complex business rules, it might be worth exploring the useReducer hook. When our app grows, and we want to fine-tune things further for performance, leverage the useCallback hook for our reset, decrement and increment handlers.

Related: