Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda