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?
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>
);
}