Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

537
Views
Why doesn't react-router-dom useParams hook work within Context?

I've got a context shared amongst a group of profile pages. The context is responsible for loading and setting the user's profile from a database, like so:

const Profile = props => {
    const { userProfile } = useContext(ProfileContext);
    return userProfile && (
        <div className="profile-container">
            ...stuff
        </div>
    );
};

export default Profile;

...routes:

<BrowserRouter>
    <Header />
    <main className="main-container">
        <Switch>
            ...other routes
            <ProfileContextProvider>
                <Route path="/profile/:id" exact component={Profile} />
                <Route path="/settings" exact component={Settings} />
            </ProfileContextProvider>
        </Switch>                       
    </main>
    <Footer />
</BrowserRouter>

The context itself is very simple:

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";

export const ProfileContext = React.createContext({
    userProfile: {},
    setUserProfile: () => {}
});

ProfileContext.displayName = "ProfileContext";

const ProfileContextProvider = props => {
    const { id } = useParams(); //always undefined!
    const [userProfile, setUserProfile] = useState(null);

    useEffect(() => {
        loadData();
    }, []);
    
    const loadData = async () => {
        ...api call to load data
    };
    
    return (
        <ProfileContext.Provider value={{ 
            userProfile,
            setUserProfile
        }}>
            {props.children}
        </ProfileContext.Provider>
    );
};

export default ProfileContextProvider;

However, that use of useParams() in there doesn't work. The "id" is always undefined. If I move this useParams() usage to the Profile component itself, it works fine. This does me no good, because I need to make a decision about the route, when loading data in the context, before I load all of Profile. I need it to work in the context!

Is this possible? Am I doing something wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Context is itself different management and query param should props from the page to context set variable then it works

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!