React: Write useToggle

Write your first custom Hook and use it twice.

What to build

Two switches made with one custom Hook.

Requirements

  • Write useToggle(initial) returning [value, toggle].
  • App uses it twice: a button with the id wifi (starting off) and a button with the id sound (starting on). Each shows NAME: on or NAME: off (Wi-Fi and Sound) and toggles itself when clicked.

Constraints

App must not call useState itself.

Example

Clicking Wi-Fi shows "Wi-Fi: on" while Sound stays "Sound: on".

Why it works

The Hook holds the toggling logic once, and each call gets its own state, so the two switches work independently.

Hints

Hint 1

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

Hint 2

Call it twice in App, once for each switch.

Solution

Show one correct solution (try it yourself first)
import { useState } from "react";

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

export default function App() {
  const [wifi, toggleWifi] = useToggle(false);
  const [sound, toggleSound] = useToggle(true);
  return (
    <div>
      <button id="wifi" onClick={toggleWifi}>
        Wi-Fi: {wifi ? "on" : "off"}
      </button>
      <button id="sound" onClick={toggleSound}>
        Sound: {sound ? "on" : "off"}
      </button>
    </div>
  );
}

Lesson: Custom Hooks: reusing stateful logic →