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]. Appuses it twice: abuttonwith the idwifi(starting off) and abuttonwith the idsound(starting on). Each showsNAME: onorNAME: off(Wi-FiandSound) 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>
);
}