AI Hints
Home›React Tutorial›Custom Hooks
React · Lesson 52 of 120

Custom Hooks

Reuse logic.

⏱ 2 min read▶ Video at 42:23🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

When two components need the same stateful logic, pull it into a custom hook. It's just a function whose name starts with use, and which calls other hooks.

  • Same logic twice
  • Pull it out
  • A function named use...

useToggle

A custom hook is a function whose name starts with use, and which calls other hooks. Use toggle keeps an on flag, and returns it with a toggle function. Each question calls it, and gets its own separate state. We open the first question. Run it.

App.jsxjsx
import { useState } from "react";
function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = () => setOn(o => !o);
  return [on, toggle];
}
function FaqItem({ id, q, a }) {
  const [open, toggle] = useToggle();
  return <div className="box"><b id={id} onClick={toggle}>{open ? "▾" : "▸"} {q}</b>{open && <p>{a}</p>}</div>;
}
export default function App() {
  return (<>
    <FaqItem id="d" q="Do you deliver?" a="Yes, anywhere in the UK." />
    <FaqItem id="r" q="Can I return a bike?" a="Yes, within 30 days." />
  </>);
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"click": "#d"}]

Custom hook rules

The name must start with use, so React can check the rules of hooks. Each call gets its own state. Hooks share logic, not state. And they can return anything you like.

keyvalue
NameuseSomething
Each callits own state
Shareslogic, not state
Returnsanything

Summary

Custom hooks package stateful logic, so components can reuse it. Next, use local storage.

Key takeaways
  • useToggle()
  • Own state per call
  • Reuse logic
Next up: useLocalStorage — remember values