Concept of Custom Hooks
The custom hooks in React allow you to extract reusable logic from your components into standalone functions. These functions can then be shared across multiple components, promoting code reuse and improving code organization.
- Create a Custom Hook: Define a function with a name that starts with “use“. This function can contain any logic you want to reuse across components.
const CustomHookUsed = (initialValue) => {
const [count, setCount] = useState(initialValue);
const handleChange = (newValue) => {
setCount(newValue);
};
return { count, handleChange };
};
- Use state and other hooks if needed: Inside your custom hook, you can use state, effects, and other hooks provided by React if necessary.
- Return values or functions: Ensure that your custom hook returns the values or functions that you want to use in your components.
- Use the custom hook in components: Import and use your custom hook in your functional components just like you would with built-in hooks.
import React from 'react';
import { CustomHookUsed } from './CustomHookUsed';
const App = () => {
// Use your custom hook
const { count, handleChange } = useCustomHook('initialValue');
return (
<div>
<input
type="text"
value={count}
onChange={(e) => handleChange(e.target.value)}
/>
</div>
);
};
export default App;
- Reuse across components: You can now reuse your custom hook across different components in your application to share the logic.
What’s the concept of custom hooks, and why do we use them?
Custom hooks in React are JavaScript functions that utilize built-in React hooks or other custom hooks to encapsulate reusable logic in functional components. They follow a naming convention where the function name starts with “use” (e.g., useCustomHook
). Custom hooks allow users to abstract complex logic into reusable units, promoting code reusability and maintainability in React applications.