Custom Hooks: Design Patterns for Interviews
⚛ ری‌اکت

Custom Hooks: Design Patterns for Interviews

Extract reusable stateful logic — fetch, media queries, localStorage, and form helpers.

BugCast Admin··۵ دقیقه مطالعه

Custom hooks share logic, not UI. Naming must start with use, and they compose built-in hooks following the same Rules of Hooks.

Common Interview Questions

Q: What makes a function a custom hook?

Answer: It calls other hooks and follows hook rules. The use prefix signals to linters and developers that hook rules apply.

Q: Implement useLocalStorage

Answer: Lazy init reads storage once. Sync effect persists changes. Handle SSR by guarding localStorage access.


function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    const stored = localStorage.getItem(key);
    return stored ? JSON.parse(stored) : initial;
  });
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
}

Q: useFetch pattern?

Answer: Track loading/error/data, abort on unmount with AbortController, and reset when URL dependency changes. Consider TanStack Query instead in production.

Q: Can hooks return JSX?

Answer: Technically yes, but convention is return state and handlers. Render props or components are clearer for UI.

Key Points for Interviews

  • Extract logic duplicated across components

  • Must obey Rules of Hooks

  • Compose smaller hooks into larger ones

  • Name with use prefix always

  • Test hooks with @testing-library/react renderHook

#custom-hooks#hooks#interview

مطالب مرتبط