🎓 A1Learner
🔍
0 of 50 lessons completed

Hooks Introduction

Hooks are functions that add extra abilities to a component. The useState Hook is one example that adds state.

A Hook at the top

The call sits at the top of the component.

const [count, setCount] = useState(0);
return <p>Count: {count}</p>;

Never inside a condition

This placement breaks the rule.

if (ready) {
  const [count, setCount] = useState(0);
}

Another Hook call

Each call adds its own piece of state.

const [name, setName] = useState('Ada');
return <p>Hello, {name}</p>;

Example

import { useState } from 'react';
export default function App() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Add one</button>
    </div>
  );
}

Key points

  • A Hook is a function that adds one ability to a component.
  • useState is a Hook that adds state to a component.
  • Hooks run at the top of a component.
  • Hooks never run inside a condition or a loop.

In this example, the component calls useState at the top. The call makes a count that starts at zero. The paragraph shows the count. The button adds one to the count on each click.

Note

A Hook call must stay in the same place on every render.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where must a Hook call sit in a component?