useBoolean Hook

EasyReact Hooks15 min5 tests

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 to true.
  • setFalse() — forces the value to false.
  • 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 useState for the boolean.
  • Wrap the helpers so each is a stable callback — useCallback is a good fit (use the functional updater for toggle).
  • setTrue and setFalse should be idempotent: calling setTrue twice in a row keeps the value true.

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)
  1. Back the hook with const [value, setValue] = useState(initial). Default the initial parameter to false.
  2. setTrue is () => setValue(true), setFalse is () => setValue(false), toggle is () => setValue(v => !v). Wrap them in useCallback so the references stay stable.
  3. In App, render the status text with a ternary: value ? 'ON' : 'OFF', inside a <span role="status">.
  4. 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

Join Us
blur