Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
How to properly change React context value?

Say i’ve declared have the following context:

const ColorContext = React.createContext(“”)

I am trying to create a simple function that can change the value of the context, which can later be used in a number of other components as a global state variable. The function i've implemented however is not doing anything to change the context value, here is what i've done, feel free to let me know where I am going wrong in the code:

function GlobalContext(){

const {color, setColor} = useContext(ColorContext);

const toGreen = () => {
setColor(‘green’);
};

 return(
   <>
    <ColorContext.Provider value={{color, setColor}}>
    <button onClick={toGreen}> Change Color </button>
    <ColorContext.Provider/>
   </>
 )
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're doing it wrong. useContext is for use in components lower in the tree than the Context's Provider. What you want in the component that renders your Context.Provider is this:

const [color, setColor] = useState();

So the whole thing would look something like this:

const ColorContext = React.createContext();

const MyColorContextProvider = ({children}) => {

  const [color, setColor] = useState(); 
  const toGreen = () => setColor('green');

  return (
   <ColorContext.Provider value={{color,setColor}}>
      {children}
      <button onClick={toGreen}>Change to Green</button>
   </ColorContext.Provider>
  );
}

and then:

const MyChildComponent = () => {
   const {color} = useContext(ColorContext);

   return <>The color in context is {color}</>
}

your app could be:

const App = () => {
  return (
   <MyColorContextProvider>
    <MyChildComponent/>
   </MyColorContextProvider>
  );
}

Stackblitz: https://stackblitz.com/edit/react-gym2ku?file=src%2FColorContextProvider.js

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda