SmartCodingTips

πŸ›  Custom Hooks in React

A **Custom Hook** lets you extract and reuse logic between components. It’s a regular function that uses built-in React hooks like useState, useEffect, etc.


πŸ”§ 1. Creating a Custom Hook

Custom hooks start with use and can contain any reusable logic.


// useCounter.js
import { useState } from 'react';

function useCounter(initialValue = 0) {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount(prev => prev + 1);
  const decrement = () => setCount(prev => prev - 1);

  return { count, increment, decrement };
}

export default useCounter;

πŸ“¦ 2. Using the Custom Hook

Use it just like a built-in hook:


import useCounter from './useCounter';

function CounterComponent() {
  const { count, increment, decrement } = useCounter(10);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
}

πŸ’‘ 3. Benefits of Custom Hooks

  • Encapsulate logic and reuse it anywhere
  • Keep components clean and readable
  • Use other hooks inside them

πŸ“Œ 4. Naming Rule

Always start with use β€” e.g., useForm, useAuth, useDarkMode. This ensures React treats it like a hook.

Custom hooks help organize logic across large apps by abstracting behavior into standalone, reusable functions.