Reputation: 4242
I want the child component Dashboard
to re-render every time I change showOfferDescription.current
.
I must use useRef
here - if I use useState
the callback functions called by game.events.on()
are ran every time using the initial value I put on that state (since they just do a copy of the initial value).
But on the other hand, if I use useRef
, the child component Dashboard
doesn't re-render when I change the refs I'm passing on props
.
How do I force it to re-render? Would this be bad practice?
export default function App = () => {
const showOfferDescription = useRef(false);
useEffect(() => {
// Must use a useRef variable here. If I use useState, the values don't update because
// the callback function just keeps a copy to the initial value and not the current value
game.events.on('POINTEROVER', (id) => {
showOfferDescription.current = true;
})
game.events.on('POINTEROUT', (id) => {
showOfferDescription.current = false;
})
}, []);
return (
// Passing a ref to the child doesn't cause re-render on change. I want to trigger
// a re-render in Dashboard everytime I change `showOfferDescription.current`
<Dashboard
showOfferDescription={showOfferDescription}
/>
);
}
Upvotes: 0
Views: 1254
Reputation: 5437
What is the problem in this one:
export default function App = () => {
const [showOfferDescription, setShowDescription] = useState(false);
useEffect(() => {
game.events.on('POINTEROVER', (id) => {
setShowDescription(true);
})
game.events.on('POINTEROUT', (id) => {
setShowDescription(false);
})
}, []);
return (
<Dashboard
showOfferDescription={showOfferDescription}
/>
);
}
Upvotes: 1