JS Guide
HomeQuestionsSearchResources
Search

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

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext
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 hook
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>
  );
}

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?