| Manage Complex Forms with React Hooks :👈 | 👉:Hook Dependency Arrays |
How to Share Logic Between React Components |
How to Share Logic Between React Components
1. Introduction
In React, multiple components often need to perform the same operations. For example, several components might need to fetch API data, validate form fields, manage a timer, track the browser's online status, or calculate values.
Copying the same logic into multiple components creates duplication and makes maintenance difficult. If the logic changes, every copy must be updated.
React provides several ways to share logic between components:
- Custom Hooks: Share stateful logic and behavior between function components.
- Utility functions: Share ordinary calculations and reusable functions.
- Context: Make shared values available to descendant components without passing them through every intermediate component.
- Render props: Share behavior by passing a function that determines what should be rendered.
- Higher-Order Components (HOCs): Share behavior by wrapping a component with another component.
- Component composition: Reuse existing components and combine them to build new interfaces.
In modern React applications, custom Hooks are usually the first choice for sharing reusable stateful logic between function components. Utility functions are often the simplest choice for logic that does not need React state or lifecycle behavior.
2. Sharing Logic by Copying Code: The Problem
Suppose two components need to fetch a user's information from an API.
Component A
import { useEffect, useState } from "react";
function UserProfile() {
const [user, setUser] = useState(null);
useEffect(() => {
fetch("/api/user")
.then(response => response.json())
.then(data => setUser(data));
}, []);
if (!user) {
return <p>Loading...</p>;
}
return <p>Welcome, {user.name}</p>;
}
export default UserProfile;
Component B
import { useEffect, useState } from "react";
function UserDetails() {
const [user, setUser] = useState(null);
useEffect(() => {
fetch("/api/user")
.then(response => response.json())
.then(data => setUser(data));
}, []);
if (!user) {
return <p>Loading...</p>;
}
return <p>User name: {user.name}</p>;
}
export default UserDetails;
Both components contain nearly identical data-fetching logic.
Problems with duplication:
- The same logic is maintained in multiple places.
- Adding error handling requires updating both components.
- Fixing a bug requires changing every copy.
- Components become harder to test and maintain.
We can solve this problem by moving the reusable behavior into a custom Hook.
3. Method 1: Share Logic Using Custom Hooks
A custom Hook is a JavaScript function whose name starts with use and that can call React Hooks, such as useState and useEffect, at the top level.
Custom Hooks allow you to extract reusable stateful logic from components without duplicating the implementation.
Step 1: Create a Custom Hook
Create a file named useUser.js.
import { useEffect, useState } from "react";
export function useUser() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
async function fetchUser() {
try {
setLoading(true);
setError(null);
const response = await fetch("/api/user", {
signal: controller.signal
});
if (!response.ok) {
throw new Error("Failed to fetch user");
}
const data = await response.json();
setUser(data);
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message);
}
} finally {
if (!controller.signal.aborted) {
setLoading(false);
}
}
}
fetchUser();
return () => {
controller.abort();
};
}, []);
return {
user,
loading,
error
};
}
What does this Hook do?
- Fetches user information from an API.
- Tracks the loading state.
- Handles request errors.
- Cancels the fetch when the component using the Hook unmounts.
- Returns the user data and request status to the calling component.
Step 2: Use the Custom Hook in Component A
import { useUser } from "./useUser";
function UserProfile() {
const { user, loading, error } = useUser();
if (loading) {
return <p>Loading user profile...</p>;
}
if (error) {
return <p role="alert">Error: {error}</p>;
}
return <p>Welcome, {user.name}</p>;
}
export default UserProfile;
Step 3: Use the Same Hook in Component B
import { useUser } from "./useUser";
function UserDetails() {
const { user, loading, error } = useUser();
if (loading) {
return <p>Loading user details...</p>;
}
if (error) {
return <p role="alert">Error: {error}</p>;
}
return (
<div>
<p>Name: {user.name}</p>
<p>Email: {user.email}</p>
</div>
);
}
export default UserDetails;
Both components now reuse the same implementation.
Important distinction: Calling useUser() separately in two components does not automatically make them share one state instance or one network request. Each Hook call has its own state and effect. If both components mount independently, both may issue a request.
If the goal is to share one user state or cache one API request across components, use a suitable shared-state approach, such as Context, a state-management library, or a data-fetching library.
4. Method 2: Share Logic Using Utility Functions
Not all reusable logic needs a custom Hook. If the logic does not depend on React state, effects, or other Hooks, a normal JavaScript function is often the best solution.
Example: Email Validation
Suppose several forms need to validate email addresses.
Step 1: Create a Utility Function
Create a file named validation.js.
export function validateEmail(email) {
if (!email.trim()) {
return "Email is required.";
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return "Enter a valid email address.";
}
return "";
}
Step 2: Reuse It in Multiple Components
import { validateEmail } from "./validation";
function LoginForm() {
const email = "user@example.com";
const error = validateEmail(email);
return (
<div>
{error
? <p>{error}</p>
: <p>Email is valid.</p>}
</div>
);
}
The same function can be imported into registration forms, profile forms, and other components.
Use utility functions for:
- Validation rules.
- Formatting dates and currency.
- Calculating totals.
- Filtering and sorting data.
- Converting data between formats.
- Pure business calculations.
A pure utility function returns a result based on its inputs and does not need React rendering or component lifecycle behavior.
5. Method 3: Share Values Using Context
Sometimes multiple components need access to the same value, such as the logged-in user, selected theme, or application settings.
Custom Hooks share the implementation of logic, while Context allows components within a provider's subtree to read a shared value.
Example: Sharing Authentication Information
Step 1: Create the Context
import { createContext } from "react";
export const AuthContext = createContext(null);
Step 2: Provide the Value
import { useState } from "react";
import { AuthContext } from "./AuthContext";
function AuthProvider({ children }) {
const [user, setUser] = useState({
name: "Alex",
role: "Admin"
});
return (
<AuthContext value={{ user, setUser }}>
{children}
</AuthContext>
);
}
export default AuthProvider;
This example uses the React 19 provider syntax. In React 18 and earlier, use <AuthContext.Provider value={{ user, setUser }}>.
Step 3: Create a Custom Hook to Consume the Context
import { useContext } from "react";
import { AuthContext } from "./AuthContext";
export function useAuth() {
const context = useContext(AuthContext);
if (context === null) {
throw new Error(
"useAuth must be used within an AuthProvider"
);
}
return context;
}
Step 4: Use the Shared Value
import { useAuth } from "./useAuth";
function UserProfile() {
const { user } = useAuth();
return <p>Welcome, {user.name}!</p>;
}
export default UserProfile;
Any descendant of AuthProvider can read the shared user value without receiving it through every intermediate component.
Remember: Context shares a value; the custom Hook provides a convenient reusable way to consume it. These techniques can be used together.
6. Method 4: Share Logic Using Render Props
The render props pattern shares behavior through a function prop that determines what the component renders.
This pattern was common before custom Hooks became widely used. It is still useful in some component APIs, but custom Hooks are usually simpler when the goal is to share logic between function components.
Example: Mouse Position
import { useEffect, useState } from "react";
function MouseTracker({ render }) {
const [position, setPosition] = useState({
x: 0,
y: 0
});
useEffect(() => {
function handleMouseMove(event) {
setPosition({
x: event.clientX,
y: event.clientY
});
}
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener(
"mousemove",
handleMouseMove
);
};
}, []);
return render(position);
}
export default MouseTracker;
Use the component like this:
function App() {
return (
<MouseTracker
render={({ x, y }) => (
<p>Mouse position: {x}, {y}</p>
)}
/>
);
}
The MouseTracker component manages the mouse position, while the calling component decides how to display it.
7. Method 5: Share Logic Using Higher-Order Components
A Higher-Order Component (HOC) is a function that accepts a component and returns a new component with additional behavior or data.
HOCs were widely used to share logic before custom Hooks were introduced.
Example: Adding a Loading Indicator
function withLoading(Component) {
return function WithLoading({ isLoading, ...props }) {
if (isLoading) {
return <p>Loading...</p>;
}
return <Component {...props} />;
};
}
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
const UserListWithLoading = withLoading(UserList);
export default UserListWithLoading;
Use the enhanced component:
<UserListWithLoading
isLoading={false}
users={[{ id: 1, name: "Alex" }]}
/>
HOCs remain useful in some libraries and legacy codebases. However, for sharing stateful behavior between modern function components, a custom Hook is usually more direct.
8. Method 6: Share UI Through Component Composition
Sometimes the duplication is not in the logic but in the UI structure. In that case, share a component instead of creating a custom Hook.
For example, multiple pages may need the same card container.
function Card({ title, children }) {
return (
<section>
<h2>{title}</h2>
<div>{children}</div>
</section>
);
}
function ProfilePage() {
return (
<Card title="Profile">
<p>User profile information</p>
</Card>
);
}
function SettingsPage() {
return (
<Card title="Settings">
<p>Application settings</p>
</Card>
);
}
Both pages reuse the same component structure while supplying different content through children.
Use component composition when the repeated part is primarily presentation or layout.
9. Custom Hooks vs Utility Functions vs Context
| Approach | Best For | Can Use React Hooks? | Shares State Automatically? |
|---|---|---|---|
| Custom Hook | Reusable stateful logic and effects | Yes | No. Each Hook call normally has independent state. |
| Utility Function | Calculations, formatting, and validation | No | No |
| Context | Values needed by multiple descendants | Consumed through Hooks such as useContext | Consumers read the provider's shared value. |
| Render Props | Sharing behavior while allowing custom rendering | The component can use Hooks internally | Depends on the component's implementation. |
| Higher-Order Component | Wrapping components with reusable behavior | The returned component can use Hooks | Depends on the HOC's implementation. |
| Component Composition | Reusable UI and layout | Components can use Hooks internally | Not inherently; it depends on the state design. |
10. How to Choose the Right Approach
Use the following decision guide when deciding how to share code in a React application.
- Is it a calculation or validation rule? Use a utility function.
- Does it involve state, effects, subscriptions, or other React Hooks? Consider a custom Hook.
- Do many descendants need the same shared value? Consider Context.
- Does the shared behavior need to provide customizable rendered output? Consider component composition or, where appropriate, render props.
- Are you maintaining a codebase that already uses HOCs? Understand and reuse the existing pattern when appropriate; avoid introducing extra wrappers without a clear benefit.
- Is the repeated part primarily visual? Extract a reusable component.
- Do multiple components need one shared server-data cache? Consider a data-fetching library or another shared caching solution rather than assuming a custom Hook will share requests.
11. Common Mistakes When Sharing Logic
- Using a custom Hook for simple calculations: A normal function is often simpler when no React Hooks are required.
- Assuming custom Hooks share state: Each invocation has its own Hook state unless the implementation uses a separate shared-state mechanism.
- Calling Hooks conditionally: Hooks must follow the Rules of Hooks. Call them at the top level of a function component or custom Hook, not inside loops, conditions, or nested callbacks.
- Putting unrelated logic into one large Hook: Keep Hooks focused on one clear responsibility.
- Using Context for every value: Props are often simpler when data is needed by only a parent and a child.
- Forgetting effect cleanup: Remove event listeners, clear timers, and cancel supported requests when appropriate.
- Duplicating business rules: Move shared calculations and validation into reusable functions or a well-defined domain layer.
- Creating abstractions too early: Extract reusable logic when there is a clear shared responsibility rather than building a complex abstraction for code that may never be reused.
12. Best Practices
- Prefer custom Hooks for reusable stateful behavior in function components.
- Prefer utility functions for pure calculations, formatting, and validation.
- Use Context when multiple descendants need access to a shared value.
- Separate shared business logic from presentation where doing so improves clarity.
- Keep each custom Hook focused and give it a descriptive name beginning with
use. - Follow the Rules of Hooks and keep dependency arrays correct.
- Clean up external subscriptions, timers, and other resources managed by effects.
- Write tests for shared logic independently when practical.
- Do not assume separate custom Hook calls share state, network requests, or caches.
- Choose the simplest pattern that clearly expresses the requirement.
13. Interview Questions and Answers
Q1. What is a custom Hook in React?
A custom Hook is a JavaScript function whose name begins with use and that can call other React Hooks. It allows stateful logic to be reused across function components.
Q2. What is the difference between a custom Hook and a utility function?
A custom Hook can use React Hooks and participate in component state and effect behavior. A utility function is an ordinary JavaScript function that does not call React Hooks and is often used for calculations or data transformations.
Q3. Do custom Hooks share state between components?
No. Calling the same custom Hook in two components normally creates independent state for each call. Use Context, an external store, or a suitable state-management library when components must share one state instance.
Q4. When should you use Context instead of a custom Hook?
Context is useful when multiple descendants need to access the same provided value. A custom Hook can wrap Context consumption to provide a convenient API, so the two approaches are often used together.
Q5. What is a Higher-Order Component?
A Higher-Order Component is a function that accepts a component and returns another component with additional behavior or data.
Q6. What are render props?
Render props are a pattern in which a component receives a function prop and calls it to determine what should be rendered, allowing behavior to be shared while leaving presentation customizable.
Q7. How do you share API-fetching logic?
You can encapsulate fetching, loading state, and error handling in a custom Hook. If multiple components need the same cached server data or request deduplication, use an appropriate shared data-fetching solution.
Q8. Can custom Hooks return multiple values?
Yes. A custom Hook can return an object, array, function, or other value that exposes the state and operations the consuming component needs.
Q9. When should you extract a reusable component instead of a Hook?
Extract a reusable component when the duplicated part is primarily UI or layout. Extract a Hook when the duplicated part is behavior or stateful logic.
Q10. What are the Rules of Hooks?
Call Hooks only at the top level of function components or custom Hooks, and do not call them conditionally, inside loops, or inside ordinary nested functions. This lets React preserve the correct Hook order between renders.
14. Summary
React offers several patterns for sharing logic, and each is suited to a different requirement.
- Custom Hooks: Share reusable stateful logic.
- Utility functions: Share calculations, formatting, and validation.
- Context: Make shared values available across a component subtree.
- Render props: Share behavior with customizable rendering.
- Higher-Order Components: Add reusable behavior by wrapping components.
- Component composition: Share UI and layout.
Key takeaway: Use a utility function for ordinary reusable logic, a custom Hook for reusable React behavior, Context for shared descendant-accessible values, and a reusable component for repeated UI. Combine these patterns when necessary, but avoid unnecessary abstraction.
| Manage Complex Forms with React Hooks :👈 | 👉:Hook Dependency Arrays |
Comments and Discussion