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

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

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 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