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

239
Views
How can I pass a state from a function component so i can use it in the use-Context

so am trying to get some data in a form of a state in react.js and i need to use it in the useContext so i can perform an Api call so please if someone can help that would be a please <3 and really helpful and thank you

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

0

If I understand your question correctly, you can do:

// MyComponent.js

import React, { useState, createContext } from "react";

// Note that you have to export the context to use it elsewhere
export const MyContext = createContext(null);

const MyComponent = () => {
 const [myState, setMyState] = useState();

 // Provider provides the context to components that are nested under it
 return (
  <MyContext.Provider value={{ myState: myState, setMyState: setMyState }}>
   <MyChildrenComponents />
  </MyContext.Provider>
 );
};

value is accessible in any component that's nested under the provider. In this case, the provider is <MyContext.Provider>. And value is accessible in <MyChildrenComponents />.

--

To extract value, we use useContext as such:

// MyChildrenComponents.js

import React, { useContext } from 'react';
import { MyContext } from './MyComponent.js';

const MyChildrenComponents = () => {
  const { myState, setMyState } = useContext(MyContext);
  
  // ...
}

You can read more about React context here (the docs).

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!