🎓 A1Learner
🔍
0 of 50 lessons completed

useState Introduction

useState is a function from React that adds state to a component. State is data that a component remembers between renders.

Import useState

The import brings useState into the file.

import { useState } from 'react';

Create state

count starts at 0. setCount changes it later.

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

Show the value

The value appears in the JSX like any variable.

<p>Count: {count}</p>

Example

import { useState } from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <p>Double: {count * 2}</p>
    </div>
  );
}

Key points

  • Import useState from react before using it.
  • Call useState with the starting value.
  • It returns a pair with the value and a setter function.
  • The setter function changes the value later.
  • The square brackets split the pair into two names.

In this example, App imports useState from react. App calls useState with 0. count starts at 0, and setCount can change it later. The first paragraph shows Count: 0. The second paragraph shows Double: 0.

Note

Call useState at the top of the component.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does useState(0) return?