90% Developers Do This Mistake — Here's the Right Way!
🚫 90% Developers Do This Mistake — Here's the Right Way ✅
Many developers **create Context API but forget to use custom hooks**, which leads to messy and repeated code. Let’s see the wrong vs right way:
❌ Wrong Way (Without Custom Hook)
import { useContext } from "react";
import { AuthContext } from "./AuthContext";
function Profile() {
const { user } = useContext(AuthContext); // 👈 directly calling useContext every time
return Welcome {user.name}
;
}
✅ Right Way (With Custom Hook)
// AuthContext.js
import { createContext, useContext } from "react";
export const AuthContext = createContext();
export function useAuth() {
return useContext(AuthContext); // 👈 custom hook for clean usage
}
// Profile.js
import { useAuth } from "./AuthContext";
function Profile() {
const { user } = useAuth(); // 👈 much cleaner!
return Welcome {user.name}
;
}
✅ Best Practice: Always create a custom hook like useAuth
for each context. It makes your code cleaner, reusable, and easier to refactor!