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>
);
};
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)