DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on • Edited 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.

Support My Work โค๏ธ

If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!

Connect with Me ๐ŸŒ

Letโ€™s stay connected! You can follow me or reach out on these platforms:

๐Ÿ”น YouTube โ€“ Tutorials, insights & tech content

๐Ÿ”น LinkedIn โ€“ Professional updates & networking

๐Ÿ”น GitHub โ€“ My open-source projects & contributions

๐Ÿ”น Instagram โ€“ Behind-the-scenes & personal updates

๐Ÿ”น X (formerly Twitter) โ€“ Quick thoughts & tech discussions

Iโ€™d love to hear from youโ€”whether itโ€™s feedback, collaboration ideas, or just a friendly hello!

Disclaimer

This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.

Top comments (0)