Reusing Logic with Custom Hooks in React JS – Complete Detailed Notes
Reusing Logic with Custom Hooks is an important React JS concept that helps developers share stateful logic between multiple functional components. Instead of writing the same state management, event handling, or Effect logic repeatedly, developers can extract that logic into a reusable function called a Custom Hook.
Custom Hooks improve code readability, maintainability, modularity, and reusability. They allow components to focus on what they display and do, while the Custom Hook handles the underlying behavior.
1. What Does Reusing Logic Mean in React?
Reusing logic means writing a piece of functionality once and using it in multiple places instead of duplicating the same code. In React, multiple components may need similar behavior, such as tracking online status, managing form inputs, fetching data, or handling a counter.
For example, a website may have a StatusBar component that displays whether the user is online and a SaveButton component that becomes disabled when the user is offline. Both components need the same online-status logic, but their user interfaces are different.
Instead of duplicating the logic in both components, we can create a Custom Hook named useOnlineStatus and use it in both components.
Benefits of Reusing Logic
- Reduces duplicate code.
- Makes components shorter and easier to understand.
- Improves code organization.
- Allows the same behavior to be reused across different interfaces.
- Makes updates easier because shared logic is maintained in one place.
- Supports easier testing and debugging.
2. What Are Custom Hooks?
A Custom Hook is a JavaScript function that uses React Hooks to encapsulate reusable logic. A Custom Hook can use built-in Hooks such as useState, useEffect, and useContext, as well as other Custom Hooks.
Custom Hooks must follow the Rules of Hooks. Their names conventionally begin with use, followed by a capital letter, such as useCounter, useOnlineStatus, or useFormInput.
Basic Syntax
import { useState } from 'react';
function useCustomLogic(initialValue) {
const [value, setValue] = useState(initialValue);
function updateValue(newValue) {
setValue(newValue);
}
return {
value,
updateValue
};
}
export default useCustomLogic;
Explanation
useCustomLogic is the Custom Hook.
useState manages the value.
updateValue updates the state.
- The Hook returns the value and the function needed by the component.
- Any component that calls this Hook can use the returned logic.
3. Problem Without Reusing Logic
Suppose two components need to track the user's internet connection. Without a Custom Hook, the same state and browser event listeners may need to be written in both components.
Example: StatusBar Component
import { useState, useEffect } from 'react';
function StatusBar() {
const [isOnline, setIsOnline] = useState(
navigator.onLine
);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return (
<h2>
{isOnline ? 'Online' : 'Offline'}
</h2>
);
}
export default StatusBar;
Example: SaveButton Component
import { useState, useEffect } from 'react';
function SaveButton() {
const [isOnline, setIsOnline] = useState(
navigator.onLine
);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
function handleSave() {
console.log('Progress saved');
}
return (
<button
disabled={!isOnline}
onClick={handleSave}
>
{isOnline ? 'Save Progress' : 'Reconnecting...'}
</button>
);
}
export default SaveButton;
Problems With This Approach
- The online-status logic is duplicated.
- Changes must be made in multiple files.
- The components contain both interface code and connection-tracking logic.
- Repeated code makes maintenance more difficult.
4. Solution: Extract the Logic into a Custom Hook
We can move the repeated state and browser event-handling logic into a single Custom Hook called useOnlineStatus. Both components can then call the Hook instead of repeating the implementation.
Step 1: Create useOnlineStatus.js
import { useState, useEffect } from 'react';
export function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(
navigator.onLine
);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline;
}
Step 2: Use the Hook in StatusBar.jsx
import { useOnlineStatus } from './useOnlineStatus';
function StatusBar() {
const isOnline = useOnlineStatus();
return (
<h2>
{isOnline ? 'Online' : 'Offline'}
</h2>
);
}
export default StatusBar;
Step 3: Use the Hook in SaveButton.jsx
import { useOnlineStatus } from './useOnlineStatus';
function SaveButton() {
const isOnline = useOnlineStatus();
function handleSave() {
console.log('Progress saved');
}
return (
<button
disabled={!isOnline}
onClick={handleSave}
>
{isOnline ? 'Save Progress' : 'Reconnecting...'}
</button>
);
}
export default SaveButton;
Step 4: Use Both Components in App.jsx
import StatusBar from './StatusBar';
import SaveButton from './SaveButton';
function App() {
return (
<div>
<StatusBar />
<SaveButton />
</div>
);
}
export default App;
How It Works
- The Custom Hook tracks the browser's online status.
- The browser fires an online or offline event when its connection status changes.
- The Hook updates its state in response to the event.
- StatusBar displays the current status as text.
- SaveButton uses the same logic to enable or disable the button.
- Both components reuse the same implementation without duplicating the code.
Important: The two components have separate Hook state and Effect instances. They both respond to browser online/offline events, but the Custom Hook does not automatically make their state a single shared state variable. Also, navigator.onLine indicates the browser's reported connection status; it does not guarantee that a particular server is reachable.
5. How Custom Hooks Improve Code Reusability
Custom Hooks separate reusable behavior from the user interface. A component no longer needs to know every detail of how a behavior works internally; it can call a Hook and use the returned values.
| Without Custom Hooks |
With Custom Hooks |
| Repeated logic in different components. |
Shared logic is maintained in one Hook. |
| Components contain more implementation details. |
Components focus on their interface and purpose. |
| Updates may require changes in several places. |
Shared behavior can be updated centrally. |
| Code may be harder to test and maintain. |
Logic can be tested and maintained separately. |
| Repeated code can increase inconsistencies. |
Consistent behavior can be reused across components. |
6. Reusing Form Input Logic with useFormInput
Forms often contain several inputs. Each input may need state, a change handler, a value, and an onChange property. A Custom Hook can encapsulate this repeated logic.
Step 1: Create useFormInput.js
import { useState } from 'react';
export function useFormInput(initialValue = '') {
const [value, setValue] = useState(initialValue);
function handleChange(event) {
setValue(event.target.value);
}
return {
value,
onChange: handleChange
};
}
Step 2: Reuse the Hook in a Form
import { useFormInput } from './useFormInput';
function RegistrationForm() {
const firstName = useFormInput('');
const lastName = useFormInput('');
const email = useFormInput('');
function handleSubmit(event) {
event.preventDefault();
console.log({
firstName: firstName.value,
lastName: lastName.value,
email: email.value
});
}
return (
<form onSubmit={handleSubmit}>
<input
placeholder="First Name"
value={firstName.value}
onChange={firstName.onChange}
/>
<input
placeholder="Last Name"
value={lastName.value}
onChange={lastName.onChange}
/>
<input
type="email"
placeholder="Email"
value={email.value}
onChange={email.onChange}
/>
<button type="submit">Register</button>
</form>
);
}
export default RegistrationForm;
Benefits
- The same input logic is reused for all three fields.
- Each call to useFormInput maintains its own independent value.
- The component contains less repeated state-management code.
- The Hook can be reused in other forms.
7. Reusing API Fetching Logic with a Custom Hook
Applications often need to retrieve data from APIs. A reusable data-fetching Hook can manage loading status, response data, and errors.
Example: useFetch.js
import { useEffect, useState } from 'react';
export function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(Boolean(url));
const [error, setError] = useState(null);
useEffect(() => {
if (!url) {
setData(null);
setError(null);
setLoading(false);
return;
}
const controller = new AbortController();
async function loadData() {
setLoading(true);
setError(null);
try {
const response = await fetch(url, {
signal: controller.signal
});
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
const result = await response.json();
setData(result);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message || 'Unable to fetch data');
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
loadData();
return () => {
controller.abort();
};
}, [url]);
return { data, loading, error };
}
Using useFetch in a Component
import { useFetch } from './useFetch';
function UserList() {
const {
data: users,
loading,
error
} = useFetch('https://jsonplaceholder.typicode.com/users');
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return <p>Error: {error}</p>;
}
return (
<div>
<h2>Users</h2>
<ul>
{users?.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
export default UserList;
The same Hook can be used by other components that need similar request behavior. The URL is passed as an input, and the Hook returns the data, loading state, and error state.
Note: This example illustrates reusable fetching logic. Larger applications may benefit from a data-fetching library that provides caching, retries, request deduplication, and more advanced synchronization.
8. Passing Values Between Custom Hooks
Custom Hooks can receive props, state values, and other reactive values as arguments. They can also pass returned values into other Hooks. When the component re-renders, the Custom Hook receives the latest arguments.
Example
import { useState } from 'react';
function useGreeting(name) {
return `Hello, ${name}!`;
}
function GreetingApp() {
const [name, setName] = useState('Alex');
const greeting = useGreeting(name);
return (
<div>
<h2>{greeting}</h2>
<input
value={name}
onChange={event => setName(event.target.value)}
/>
</div>
);
}
export default GreetingApp;
This example illustrates passing reactive data into a reusable function, but useGreeting does not call any React Hooks. Therefore, it is better named a regular function such as getGreeting rather than a Custom Hook.
Correct Version Using a Regular Function
function getGreeting(name) {
return `Hello, ${name}!`;
}
function GreetingApp() {
const [name, setName] = useState('Alex');
const greeting = getGreeting(name);
return (
<div>
<h2>{greeting}</h2>
<input
value={name}
onChange={event => setName(event.target.value)}
/>
</div>
);
}
Key point: A function should generally be called a Custom Hook when it uses React Hooks or is intentionally designed as a Hook. A normal function that only transforms data should remain a regular JavaScript function.
9. Sharing Logic Is Different from Sharing State
One of the most important concepts in Custom Hooks is that they share logic, not automatically the same state. Each call to a Custom Hook runs its own Hook logic and creates its own state instances.
Example
function CounterOne() {
const { count, increment } = useCounter(0);
return (
<button onClick={increment}>
Counter One: {count}
</button>
);
}
function CounterTwo() {
const { count, increment } = useCounter(0);
return (
<button onClick={increment}>
Counter Two: {count}
</button>
);
}
CounterOne and CounterTwo each maintain an independent counter. Clicking one button does not automatically update the other counter.
How to Share the Same State
- Lift state up: Move the state to a common parent and pass the value and update function through props.
- Use Context: Share values across a component tree when appropriate.
- Use a state-management library: For complex shared-state requirements, consider a suitable external state solution.
10. When Should You Create a Custom Hook?
Custom Hooks are useful when you want to reuse a meaningful piece of stateful logic or isolate synchronization with an external system.
- When multiple components repeat the same stateful behavior.
- When several components need to track online status or browser events.
- When form fields repeat the same state and change-handling logic.
- When API requests require reusable loading and error management.
- When a component's Effect logic is complex and can be extracted into a focused, purpose-specific Hook.
- When you want components to express intent clearly, such as
useChatRoom or useOnlineStatus.
When Not to Create a Custom Hook
- When the logic is a simple calculation and does not use React Hooks.
- When extracting the code makes the implementation more complicated instead of clearer.
- When there is no meaningful behavior to reuse or encapsulate.
- When a regular JavaScript function is sufficient.
You do not need to create a Custom Hook for every small piece of repeated code. The goal is clearer, more reusable logic—not creating the maximum possible number of Hooks.
11. Rules of Hooks for Reusing Logic
- Always start Custom Hook names with
use followed by a capital letter.
- Call Hooks at the top level of React components or Custom Hooks.
- Never call Hooks inside loops, conditions, or nested functions.
- Keep render-time logic pure.
- Include all relevant reactive dependencies in Effects and memoized callbacks.
- Return cleanup functions from Effects when subscriptions, listeners, or other resources need cleanup.
- Use a regular function for logic that does not need React Hooks.
- Do not rely on a Custom Hook call to create shared global state automatically.
12. Common Mistakes When Reusing Logic
Mistake 1: Copying and Pasting the Same Logic
Problem: Multiple components contain separate copies of the same stateful behavior.
Solution: Extract the shared behavior into a focused Custom Hook when doing so improves clarity and maintainability.
Mistake 2: Expecting a Custom Hook to Share State Automatically
Problem: Developers assume that calling the same Hook in two components means both components use one state variable.
Solution: Lift state to a common parent or use Context or another shared-state solution when a single shared value is required.
Mistake 3: Using the use Prefix for Ordinary Functions
Problem: A regular calculation function is named like a Hook even though it does not use React Hooks.
Solution: Use descriptive names such as getGreeting, formatPrice, or sortProducts for ordinary functions.
Mistake 4: Forgetting Cleanup
Problem: Event listeners, timers, or subscriptions remain active after they are no longer needed.
Solution: Return a cleanup function from useEffect where required.
Mistake 5: Ignoring Dependencies
Problem: Effects may use outdated values or fail to respond correctly to changes.
Solution: Include reactive values used by the Effect in its dependency array and follow the React Hooks lint rules.
13. Advantages of Reusing Logic with Custom Hooks
- Code reuse: The same stateful behavior can be used in different components.
- Maintainability: Shared behavior is updated in one location.
- Readability: Components can focus on rendering and user interaction.
- Modularity: Application logic is divided into focused units.
- Testability: Hook behavior can be tested separately from the interface when appropriate.
- Consistency: Components use the same implementation for common behavior.
- Flexibility: The same logic can support different interfaces.
14. Limitations of Custom Hooks
- Each call has independent state unless state is explicitly shared through another mechanism.
- Overusing Custom Hooks can make simple code harder to follow.
- Incorrect dependencies can create stale values or unexpected Effect behavior.
- Complex Hooks may need careful testing and documentation.
- Custom Hooks do not automatically improve performance; their main purpose is logic reuse and organization.
15. Practical Project: Reusable Counter Logic
Build a counter Hook that can be reused by different components. The Hook will provide a current count and functions to increment, decrement, and reset it.
File 1: useCounter.js
import { useState } from 'react';
export function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
function increment() {
setCount(previousCount => previousCount + 1);
}
function decrement() {
setCount(previousCount => previousCount - 1);
}
function reset() {
setCount(initialValue);
}
return {
count,
increment,
decrement,
reset
};
}
File 2: CounterPanel.jsx
import { useCounter } from './useCounter';
function CounterPanel() {
const {
count,
increment,
decrement,
reset
} = useCounter(0);
return (
<section>
<h2>Reusable Counter</h2>
<p>Current Count: {count}</p>
<button onClick={increment}>Increase</button>
<button onClick={decrement}>Decrease</button>
<button onClick={reset}>Reset</button>
</section>
);
}
export default CounterPanel;
File 3: App.jsx
import CounterPanel from './CounterPanel';
function App() {
return (
<main>
<h1>Custom Hooks Demo</h1>
<CounterPanel />
</main>
);
}
export default App;
Project Learning Outcomes
- Created a reusable stateful Hook.
- Separated counter logic from the user interface.
- Used the Hook in a React component.
- Learned how a Custom Hook can be extended and reused in other components.
16. Frequently Asked Interview Questions
Q1. What does reusing logic mean in React?
It means using the same behavior or implementation in multiple components rather than duplicating the code.
Q2. How do Custom Hooks help reuse logic?
They encapsulate Hook-based behavior in a function that can be called by multiple components.
Q3. What is the naming convention for Custom Hooks?
Custom Hook names begin with use followed by a capital letter, such as useCounter.
Q4. Can multiple components use the same Custom Hook?
Yes. Multiple components can call the same Custom Hook to reuse its logic.
Q5. Do Custom Hooks share state between components?
No. Each call creates its own state instances. Shared state requires a common owner or an explicit shared-state mechanism.
Q6. Can a Custom Hook use useEffect?
Yes. A Custom Hook can use useEffect to synchronize with external systems, such as browser events or subscriptions.
Q7. When should logic be extracted into a Custom Hook?
Extract logic when it represents a meaningful reusable behavior or when doing so makes a component clearer and easier to maintain.
Q8. Is every reusable function a Custom Hook?
No. Ordinary JavaScript functions are appropriate for calculations and transformations that do not use React Hooks.
Q9. Can Custom Hooks accept parameters?
Yes. They can receive props, state values, configuration objects, and other inputs required by the reusable logic.
Q10. Can one Custom Hook call another Custom Hook?
Yes. Custom Hooks can compose built-in Hooks and other Custom Hooks while following the Rules of Hooks.
Q11. What is the benefit of extracting Effect logic?
It can make data flow more explicit and allow components to focus on their purpose instead of implementation details.
Q12. Do Custom Hooks automatically improve performance?
No. They primarily improve logic reuse and organization. Performance optimizations should be added when they are necessary and beneficial.
17. Practice Exercises
- Create a
useCounter Hook and use it in two different components.
- Create a
useFormInput Hook to reuse form input logic.
- Create a
useOnlineStatus Hook that listens for browser online and offline events.
- Create a
useToggle Hook for showing and hiding a menu.
- Create a
useFetch Hook that manages loading, data, and errors.
- Refactor duplicated logic from two components into one Custom Hook.
- Demonstrate that two calls to the same Custom Hook maintain independent state.
- Share a single state value between sibling components using a common parent.
18. Quick Revision Checklist
- ☑ Reusing logic avoids unnecessary duplication.
- ☑ Custom Hooks encapsulate reusable Hook-based behavior.
- ☑ Custom Hook names start with
use.
- ☑ Custom Hooks can use built-in Hooks and other Custom Hooks.
- ☑ Each Custom Hook call has independent state.
- ☑ Shared state requires lifting state or using a suitable shared-state mechanism.
- ☑ Effects may require cleanup for listeners, subscriptions, and timers.
- ☑ Regular JavaScript functions should be used for simple calculations that do not need Hooks.
- ☑ Custom Hooks should have a clear and focused purpose.
- ☑ Follow the Rules of Hooks and manage dependencies correctly.
19. Official React Documentation
20. React JS Training Resources
To learn more about React JS, component development, state management, Hooks, and reusable application logic, explore the following resources:
21. Conclusion
Reusing logic with Custom Hooks is a powerful React development technique that helps reduce duplication and improve code organization. By extracting common behavior into Hooks such as useOnlineStatus, useFormInput, and useCounter, developers can create cleaner and more maintainable components. Remember that Custom Hooks share logic rather than automatically sharing state, and always follow the Rules of Hooks when creating reusable functionality.