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

126
Vistas
Use value in one component and reset in another

I have a simple ReactJS component, that makes use of some state, myValue, which is stored in a context.

On this page I render myValue in some HTML, and also in a button.

I want the original value of myValue to be rendered in the HTML, but I want to set the value in the context to be 0.

The button should always display the value held in the context, which should be rendered as 0 on the page.

export function MyComponent() {
    const { myValue, setMyValue } = useContext(myValueContext);

    useClearData(); // Should be called somewhere to reset myValue to 0

    return (
        <React.Fragment>
            <MyValueButton /> {/* Should display myValue as 0 */}
            <main className="App">
                <div>
                    My value is the original {myValue} which should be non-zero!
                </div>
            </main>
        </React.Fragment>
    );
}

How do I structure this code so that the button re-renders when the context changes, but the HTML does not?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So, to answer my own question, this needs the useRef hook:

export function MyComponent() {
    const { myValue, setMyValue } = useContext(myValueContext);
    myValueRef = useRef(myvalue);
    useClearData(); // Should be called somewhere to reset myValue to 0

    return (
        <React.Fragment>
            <MyValueButton /> {/* Should display myValue as 0 */}
            <main className="App">
                <div>
                    My value is the original {myValueRef.current.toString()} which should be non-zero!
                </div>
            </main>
        </React.Fragment>
    );
}
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