useBoolean Hook
Build a reusable useBoolean hook that manages a boolean flag with explicit setTrue, setFalse, and toggle helpers, then wire it to On/Off/Toggle buttons and a live ON/OFF status readout.
A custom hook is the idiomatic way to package a small, reusable piece of stateful logic in React. One of the most common is a boolean flag: think modals (open/closed), dropdowns, feature switches, and "show more" toggles.
In this exercise you'll implement useBoolean(initial = false). It returns an object with four members:
value— the current boolean.setTrue()— forces the value totrue.setFalse()— forces the value tofalse.toggle()— flips the value.
You'll then drive a tiny UI with it: an On button (calls setTrue), an Off button (calls setFalse), a Toggle button (calls toggle), and a live region with role="status" that reads ON when the value is true and OFF when it is false.
The hook must live inside App.tsx and the default-export App component must use it. The initial value should be false, so the status starts as OFF.
Implementation tips:
- Use
useStatefor the boolean. - Wrap the helpers so each is a stable callback —
useCallbackis a good fit (use the functional updater fortoggle). setTrueandsetFalseshould be idempotent: callingsetTruetwice in a row keeps the valuetrue.
Requirements
- Implement a useBoolean(initial = false) hook inside App.tsx that returns { value, setTrue, setFalse, toggle }.
- The default-export App component must use the hook to drive its UI.
- Render three real <button> elements labeled On, Off, and Toggle.
- Render an element with role="status" that displays "ON" when value is true and "OFF" when value is false.
- The initial rendered status must be "OFF" (initial value defaults to false).
- Clicking On sets the value true; Off sets it false; Toggle flips it.
- setTrue and setFalse must be idempotent (repeated clicks keep the same value).
Hints (4)
- Back the hook with const [value, setValue] = useState(initial). Default the initial parameter to false.
- setTrue is () => setValue(true), setFalse is () => setValue(false), toggle is () => setValue(v => !v). Wrap them in useCallback so the references stay stable.
- In App, render the status text with a ternary: value ? 'ON' : 'OFF', inside a <span role="status">.
- Wire each button's onClick directly to the corresponding helper returned by the hook.
Topics
- React
- React Hooks
Asked at
Zomato · Razorpay · CRED · PhonePe · Paytm · Zerodha
