JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext

Learn the concept

Hooks

react
mid
hooks

What are custom hooks and how do you create them?

custom-hooks
hooks
reusability
abstraction
composition
Quick Answer

Custom hooks are JavaScript functions starting with 'use' that encapsulate reusable stateful logic. They can use other hooks and share logic between components without duplicating code or adding components to the tree.

Detailed Explanation

What Custom Hooks Do:

  • Extract and reuse stateful logic
  • Compose built-in hooks into reusable units
  • Share behavior without render props or HOCs
  • Keep components clean and focused

Rules for Custom Hooks:

  1. Name must start with 'use' (useXxx)
  2. Can call other hooks
  3. Each call creates independent state
  4. Can return anything (values, arrays, objects)

Common Custom Hook Patterns:

  • Data fetching (useFetch)
  • Form handling (useForm)
  • Local storage (useLocalStorage)
  • Window events (useWindowSize)
  • Timers (useInterval, useDebounce)

Code Examples

useLocalStorage hookJSX
function useLocalStorage(key, initialValue) {
  // Get stored value or use initial
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });
  
  // Update localStorage when value changes
  const setValue = (value) => {
    try {
      // Allow value to be a function (like useState)
      const valueToStore = value instanceof Function 
        ? value(storedValue) 
        : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error(error);
    }
  };
  
  return [storedValue, setValue];
}

// Usage
function App() {
  const [theme, setTheme] = useLocalStorage('theme', 'light');
  const [user, setUser] = useLocalStorage('user', null);
  
  return (
    <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
      Theme: {theme}
    </button>
  );
}

Real-World Applications

Use Cases

API Integration Layer

Custom hooks encapsulating API calls, caching, error handling, and retry logic

Form Validation

Reusable form hooks that handle validation rules, error messages, and submission state

Analytics Tracking

Custom hooks that track page views, user interactions, and feature usage

Mini Projects

useForm Hook

intermediate

Build a comprehensive form hook with validation, dirty tracking, and submission handling

useWebSocket Hook

advanced

Create a hook that manages WebSocket connections with reconnection, heartbeat, and message queuing

Industry Examples

Vercel (SWR)

Custom hook useSWR for data fetching with stale-while-revalidate strategy

React Use

Collection of 100+ community custom hooks for common React patterns

Resources

React Docs - Reusing Logic with Custom Hooks

docs

useHooks - Collection of React Hooks

article

Related Questions

Explain the useState and useEffect hooks and their common patterns.

mid
hooks

What is useRef and when should you use it?

mid
hooks
Previous
What is React Context and when should you use it?
Next
What is useRef and when should you use it?
PrevNext