0
0
ReactHow-ToBeginner · 3 min read

How to Create Custom Hook in React: Simple Guide

To create a custom hook in React, define a function starting with use that uses built-in hooks inside it. This function can then be reused in components to share logic cleanly.
📐

Syntax

A custom hook is a JavaScript function whose name starts with use. Inside, you can use React hooks like useState or useEffect. It returns values or functions that components can use.

  • Function name: Must start with use to follow React rules.
  • Inside function: Use React hooks to manage state or side effects.
  • Return: Return data or functions to be used by components.
javascript
function useCustomHook(initialValue) {
  const [state, setState] = React.useState(initialValue);
  React.useEffect(() => {
    // side effect code
  }, []);
  return [state, setState];
}
💻

Example

This example shows a custom hook useCounter that manages a counter state with increment and decrement functions. Components can use it to get and change the counter easily.

javascript
import React from 'react';

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

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

  return { count, increment, decrement };
}

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

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

export default Counter;
Output
Count: 5 [Increase button] [Decrease button]
⚠️

Common Pitfalls

Common mistakes when creating custom hooks include:

  • Not starting the function name with use, which breaks React rules and causes errors.
  • Using hooks conditionally inside the custom hook, which can cause unpredictable behavior.
  • Not returning useful values or functions, making the hook less reusable.
javascript
/* Wrong: hook name does not start with 'use' */
function customHook() {
  const [value, setValue] = React.useState(0);
  return [value, setValue];
}

/* Right: hook name starts with 'use' */
function useCustomHook() {
  const [value, setValue] = React.useState(0);
  return [value, setValue];
}
📊

Quick Reference

  • Name: Start with use
  • Use hooks: Call React hooks inside your custom hook
  • Return: Return state, functions, or values for reuse
  • Rules: Do not call hooks conditionally or inside loops

Key Takeaways

Always start custom hook names with 'use' to follow React rules.
Use built-in hooks inside your custom hook to manage state or effects.
Return useful data or functions so components can reuse the logic.
Never call hooks conditionally inside your custom hook.
Custom hooks help keep your components clean and logic reusable.