A common example of sharing logic between components is handling a user authentication flow. Instead of duplicating the logic in multiple components, you can extract the logic into a custom hook and reuse it across multiple components.
import { useState, useEffect } from 'react';
function useAuth() {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const fetchUser = async () => {
const response = await fetch('/api/user');
const data = await response.json();
setUser(data);
setIsLoading(false);
};
fetchUser();
}, []);
return { user, isLoading };
}
In this example, we have created a custom hook useAuth
that handles the logic of fetching the current user from the server. The hook uses the useState
and useEffect
hooks to handle the state and side effects of fetching the user. The hook returns an object with the current user and a loading state.
We can now use this custom hook in multiple components to handle the user authentication flow.
function LoginPage() {
const { user, isLoading } = useAuth();
if (isLoading) {
return <div>Loading...</div>;
}
if (user) {
return <div>Welcome, {user.name}</div>;
}
return <div>Please login</div>;
}
function ProfilePage() {
const { user } = useAuth();
if (!user) {
return <div>Please login</div>;
}
return <div>Welcome, {user.name}</div>;
}
In this example, we have two components, LoginPage
and ProfilePage
, that use the useAuth
hook to handle the user authentication flow. The LoginPage
component displays a loading message while the user is being fetched, and then displays a welcome message or a login message, depending on whether the user is logged in or not. The ProfilePage
component displays a profile page with the user’s name, or a login message if the user is not logged in. By extracting the logic into a custom hook, we can easily share the logic between multiple components and make updates in one place.
In conclusion, sharing logic between components by extracting it into a custom hook is a best practice in ReactJS development, it allows for a more organized and maintainable codebase, and it makes it easy to understand about the logic of your application. By using custom hooks, you can avoid duplicating logic in multiple components, which can lead to more efficient and consistent code. Additionally, custom hooks can also be easily tested and reused across different parts of your application, which can save development time and reduce the likelihood of bugs.
In the example above, we have seen how to create a custom hook useAuth
that handles the logic of fetching the current user from the server, and then how to use that hook in multiple components to handle the user authentication flow. By following this best practice, you can make your codebase more organized, maintainable, and efficient.