Custom Hooks Intro

View saved

Why custom hooks

When two components share the same useState/useEffect pattern, move that logic into a custom hook instead of copying it.

A tiny useLocalStorage hook

Keeps a value in React state and mirrors it to localStorage.

import { useEffect, useState } from "react";

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const raw = localStorage.getItem(key);
    return raw !== null ? JSON.parse(raw) : initialValue;
  });

  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
}

function Notes() {
  const [text, setText] = useLocalStorage("notes", "");
  return (
    <textarea value={text} onChange={(e) => setText(e.target.value)} />
  );
}

Rules still apply

Custom hooks must call other hooks unconditionally at the top level—same rules as components.

Keep them focused

One hook, one job. Prefer small helpers over a giant useAppState bag.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.