Course contentsShow
← React
Lesson 960 of 2,39625. Custom HooksFree lesson

Your First Custom Hook: useToggle

Extract a simple useState pattern for boolean toggling into a reusable hook with toggle, setOn, setOff.

Your First Custom Hook: useToggle

What you'll learn: How to extract a common boolean toggling pattern into your first reusable custom hook.

The Pattern You've Been Repeating

You've probably written this code dozens of times:

const [isOpen, setIsOpen] = useState(false);

const toggle = () => setIsOpen(prev => !prev);
const open = () => setIsOpen(true);
const close = () => setIsOpen(false);

Every modal, dropdown, sidebar, and accordion uses this exact pattern. Instead of rewriting it everywhere, you can extract it into a custom hook.

Creating useToggle

A custom hook is just a function that starts with "use" and calls other hooks inside:

function useToggle(initialValue = false) {
  const [value, setValue] = useState(initialValue);

  const toggle = () => setValue(prev => !prev);
  const setOn = () => setValue(true);
  const setOff = () => setValue(false);

  return [value, { toggle, setOn, setOff }];
}

Using Your Hook

Now anywhere you need toggle behavior:

function Modal() {
  const [isOpen, { toggle, setOn, setOff }] = useToggle(false);

  return (
    <>
      <button onClick={setOn}>Open Modal</button>
      <button onClick={setOff}>Close Modal</button>
      <button onClick={toggle}>Toggle Modal</button>
    </>
  );
}

Why This Works

Custom hooks follow the same rules as built-in hooks. They encapsulate stateful logic and return whatever API makes sense. You're not creating new React magic—you're just organizing your existing useState calls into a reusable package.

Key Takeaway: Custom hooks extract repetitive useState patterns into reusable functions. useToggle bundles boolean state with toggle/on/off helpers, eliminating boilerplate across your components.