The useState Hook

Understanding useState

The useState hook allows function components to manage state. Unlike props, which are passed to a component, state variables are internal to a component and cause re-renders when updated.

Learning Goals

After reading this article, you should be able to:

Using the useState Hook

The useState hook returns an array with two values:


import { useState } from 'react';

function App() {
  const [count, setCount] = useState(0);

  return (
    

Count: {count}

); }

Understanding Setter Functions

Setter functions update state values, but the update takes effect on the next render.


function App() {
  const [count, setCount] = useState(0);

  if (count === 0) setCount(1);
  console.log(count);

  return 

Count: {count}

; }

The console will show:

0
1

Using Updater Functions

To ensure state updates happen sequentially, use an updater function:


function App() {
  const [count, setCount] = useState(0);

  if (count === 0) {
    setCount(prevCount => prevCount + 1);
    setCount(prevCount => prevCount + 1);
    setCount(prevCount => prevCount + 1);
  }

  return 

Count: {count}

; }

Now, the rendered output will be:

Count: 3

Using useState for Controlled Inputs

The useState hook is commonly used for managing form inputs:


function FormWithHooks() {
  const [inputValue, setInputValue] = useState('');

  return (
    
setInputValue(e.target.value)} placeholder="Type something!" />
); }

This pattern keeps the input field and state synchronized, making the input a controlled input.

What You Have Learned

In this reading, you learned:

Further Exploration

To learn more, visit:

Conclusion

The useState hook is fundamental in React applications, allowing components to maintain internal state and respond to user interactions.