🔧 Error Fixes
· 1 min read

React useContext Returns Undefined — How to Fix It


TypeError: Cannot destructure property 'user' of useContext(...) as it is undefined

useContext returns undefined when the component isn’t inside the matching Provider.

Fix 1: Wrap With Provider

// ❌ Component is outside the Provider
function App() {
    return <UserProfile />;  // 💥 No UserContext.Provider above
}

// ✅ Wrap with Provider
function App() {
    return (
        <UserContext.Provider value={{ user: 'Alice' }}>
            <UserProfile />
        </UserContext.Provider>
    );
}

Fix 2: Provider in Wrong Location

// ❌ Provider wraps sibling, not parent
function App() {
    return (
        <div>
            <UserContext.Provider value={user}>
                <Sidebar />
            </UserContext.Provider>
            <MainContent />  // 💥 Outside provider
        </div>
    );
}

// ✅ Move Provider higher
function App() {
    return (
        <UserContext.Provider value={user}>
            <Sidebar />
            <MainContent />
        </UserContext.Provider>
    );
}

Fix 3: Default Value in createContext

// ❌ No default value
const UserContext = createContext();  // undefined by default

// ✅ Provide a default
const UserContext = createContext({ user: null, setUser: () => {} });

Fix 4: Custom Hook With Error

// ✅ Create a safe custom hook
function useUser() {
    const context = useContext(UserContext);
    if (!context) {
        throw new Error('useUser must be used within a UserProvider');
    }
    return context;
}

Fix 5: Multiple React Instances

# ❌ Two copies of React — context from one doesn't work in the other
npm ls react
# If you see multiple versions:
npm dedupe
📘