Wrap useState in your own useToggle hook and use it twice. Each call gets its own state.
React · beginner · 7 min · 28 steps · free
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>
);
}<Settings> for the first time: it calls the Settings function.useToggle(true). A custom hook is a function whose name starts with use and that calls other hooks.useState runs for the first time, so React stores the starting value for on and returns it: true.toggle is created for this call.useToggle returns [true, ƒ () => setOn(!on)].wifi = true.useState runs for the first time, so React stores the starting value for on and returns it: false.toggle is created for this call.useToggle returns [false, ƒ () => setOn(!on)].bluetooth = false.Settings returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.toggle.setOn(!on) sets the second hook's state to true.<Settings> again (render 2): it calls Settings once more, from the top.useToggle is a custom hook: a plain function whose hooks belong to the component that calls it.useState returns the value React has kept for on: true. The starting value is only used on the first render.toggle is created for this call.useToggle returns [true, ƒ () => setOn(!on)].wifi = true.useToggle is a custom hook: a plain function whose hooks belong to the component that calls it.toggle is created for this call.useToggle returns [true, ƒ () => setOn(!on)].bluetooth = true.Settings returns JSX: a description of what the screen should show, <ul>…</ul>. React has not changed the page yet.Answer: No, each has its own
Answer: React matches them by order
← useReducer: State Logic in One Place