A custom hook in React is a function that starts with 'use' and allows you to encapsulate logic that can be reused across multiple components. Custom hooks use existing React hooks (like useState, useEffect, etc.) internally and help in abstracting out reusable pieces of logic from components.
Why Use Custom Hooks?
· Reusability: Instead of duplicating logic across components, you can move that logic into a custom hook and share it.
· Separation of Concerns: Custom hooks help in keeping your component clean by moving logic (like fetching data, managing local storage, etc.) into separate, reusable functions.
Let’s build an application to understand custom hook better.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘custom-hook’
Project structure looks like below.
Step 2: Create hooks folder in src and define useLogger hook.
useLogger.js
import { useEffect } from "react";
export default function useLogger(componentName) {
useEffect(() => {
console.log(`${componentName} mounted`);
// Cleanup called when the component is unmounted
return () => {
console.log(`${componentName} unmounted`);
};
}, []); // Empty dependency array means this runs only on mount and unmount
useEffect(() => {
console.log(`${componentName} updated`);
});
}
Step 3: Create components folder in src and define Counter component.
Counter.jsx
import { useState } from "react";
import useLogger from "../hooks/useLogger";
export default function Counter() {
const [count, setCount] = useState(0);
useLogger("Counter");
return (
<>
<p>Counter : {count}</p>
<button onClick={() => setCount((currentCount) => count + 1)}>
Click Me
</button>
</>
);
}
Update App.jsx file with below content.
App.jsx
import React, { useState } from 'react';
import Counter from './components/Counter';
const App = () => {
const [isVisible, setIsVisible] = useState(true);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
{isVisible ? 'Hide Counter' : 'Show Counter'}
</button>
{isVisible && <Counter />}
</div>
);
};
export default App;
Update main.jsx with below content.
main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
createRoot(document.getElementById("root")).render(<App />);
Step 4: Build and run the application by executing below commands.
cd custom-hook npm install npm run dev
Experiment with the buttons ‘Hide Counter’ and ‘Click Me’, you can see following kind of messages in console.
You can download this application from this link.
No comments:
Post a Comment