Custom Hooks

Wrap useState in your own useToggle hook and use it twice. Each call gets its own state.

React · beginner · 7 min · 28 steps · free

What you'll learn

CustomHooks.jsx

import { useState } from 'react';

function useToggle(initial) {
  const [on, setOn] = useState(initial);
  const toggle = () => setOn(!on);
  return [on, toggle];
}

export default function Settings() {
  const [wifi, toggleWifi] = useToggle(true);
  const [bluetooth, toggleBluetooth] = useToggle(false);

  return (
    <ul>
      <li>
        Wi-Fi: {wifi ? 'on' : 'off'} <button onClick={toggleWifi}>Toggle</button>
      </li>
      <li>
        Bluetooth: {bluetooth ? 'on' : 'off'} <button onClick={toggleBluetooth}>Toggle</button>
      </li>
    </ul>
  );
}

Step by step

  1. React renders <Settings> for the first time: it calls the Settings function.
  2. Settings calls useToggle(true). A custom hook is a function whose name starts with use and that calls other hooks.
  3. useState runs for the first time, so React stores the starting value for on and returns it: true.
  4. toggle is created for this call.
  5. useToggle returns [true, ƒ () => setOn(!on)].
  6. wifi = true.
  7. The second call gets its own state, starting at false.
  8. useState runs for the first time, so React stores the starting value for on and returns it: false.
  9. toggle is created for this call.
  10. useToggle returns [false, ƒ () => setOn(!on)].
  11. bluetooth = false.
  12. Settings returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.
  13. React turns the JSX into real page elements and shows them: look at the Screen panel.
  14. You click Toggle next to Bluetooth. It calls the second toggle.
  15. setOn(!on) sets the second hook's state to true.
  16. React renders <Settings> again (render 2): it calls Settings once more, from the top.
  17. useToggle is a custom hook: a plain function whose hooks belong to the component that calls it.
  18. useState returns the value React has kept for on: true. The starting value is only used on the first render.
  19. toggle is created for this call.
  20. useToggle returns [true, ƒ () => setOn(!on)].
  21. wifi = true.
  22. useToggle is a custom hook: a plain function whose hooks belong to the component that calls it.
  23. React matches this useState by order: the second one in Settings.
  24. toggle is created for this call.
  25. useToggle returns [true, ƒ () => setOn(!on)].
  26. bluetooth = true.
  27. Settings returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.
  28. Bluetooth is on; Wi-Fi is unchanged.

Common mistakes

Best practices

Key takeaways

Check yourself

Two components call useToggle. Is the state shared?

Answer: No, each has its own

Why must hooks not be called inside if?

Answer: React matches them by order

More in Sharing State