DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to create Custom Hooks in React.js

Creating a custom hook in React is a way to reuse stateful logic between components. A custom hook is a JavaScript function that starts with the word "use" and may call other hooks. Here's a basic example of how you can create a custom hook:

import { useState, useEffect } from 'react';

// Custom hook example
const useCustomHook = (initialValue) => {
  // State
  const [value, setValue] = useState(initialValue);

  // Effect (optional)
  useEffect(() => {
    // Your logic here, if needed
    console.log('Custom hook effect triggered');

    // Cleanup (if needed)
    return () => {
      console.log('Custom hook cleanup');
    };
  }, [value]); // Dependencies for the effect

  // Custom functions or logic
  const increment = () => {
    setValue(value + 1);
  };

  const decrement = () => {
    setValue(value - 1);
  };

  // Return whatever you want to expose to the component
  return {
    value,
    increment,
    decrement,
  };
};

// Example usage in a component
const MyComponent = () => {
  // Use the custom hook
  const { value, increment, decrement } = useCustomHook(0);

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this example, useCustomHook is a custom hook that manages a state value and provides functions to increment and decrement that value. The useEffect hook is optional and can be used for any side effects or clean-up logic you need.

Remember that custom hooks can call other hooks, allowing you to compose and reuse logic across components. When creating a custom hook, it's a good practice to start its name with "use" to follow the convention established by React.

Top comments (0)