How To Create Custom Hooks In React? See Example

What Are Custom Hooks?

Custom hooks are functions that start with use and allow you to reuse stateful logic across multiple functional components in React.


Why Use Custom Hooks

  • Reuse logic between components
  • Keep components clean and simple
  • Avoid duplicating code
  • Make code more readable and maintainable

Example: useCounter Hook

import { useState } from "react";

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

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);
  const reset = () => setCount(initialValue);

  return { count, increment, decrement, reset };
}

Using the Custom Hook

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={increment}>Increase</button>
      <button onClick={decrement}>Decrease</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

Tips for Creating Custom Hooks

  • Always start with use
  • Return an object or array of values and functions
  • Use existing hooks like useState or useEffect inside
  • Keep them focused on one task or feature

Conclusion

Custom hooks help reuse logic efficiently, keeping your React functional components clean, modular, and maintainable.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *