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

127
Views
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 answers
Answer question

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