mediumFrontend

What are React custom hooks and when should you use them?

820 views
01

Understand the problem

Creating reusable logic across functional components.

hooksreusability
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

A useToggle custom hook
import { useState, useCallback } from "react";

function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn((v) => !v), []);
  return [on, toggle];
}

export default function App() {
  const [open, toggleOpen] = useToggle();   // each caller → its own state
  const [dark, toggleDark] = useToggle(true);
  return (
    <div style={{ padding: 24, fontFamily: "system-ui", background: dark ? "#111" : "#fff", color: dark ? "#fff" : "#111" }}>
      <button onClick={toggleOpen}>{open ? "Close" : "Open"} panel</button>
      <button onClick={toggleDark}>Toggle theme</button>
      {open && <p>Panel content</p>}
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.