I'm trying to get a functional component to force a rerender whenever the testFn
executes. I thought to use state to do this (if there's a better way then please speak up), which appears to successfully force a rerender but only twice, then nothing.
I built a simple demo to emulate the issue as using my real app is too difficult to demonstrate but the same principles should presumably apply (my real demo fetches data when the function executes and displays it on the page, but it's not rerendering and I have to refresh the page to see the new data, hence why I want to trigger a rerender).
import React, { useState } from "react";
const App = () => {
const [, rerender] = useState(false);
const testFn = () => {
console.log("test Fn");
rerender(true);
};
return (
<div>
<p>test</p>
<button onClick={testFn}>clickk</button>
{console.log("render")}
</div>
);
};
export default App;
I've also made a Stackblitz demo for conveinence.
Can anyone solve this demo or think of a better way of implementing it?
Thanks for any help here.
It triggers a re-render when the state changes.
The first time you click the button you change the state from false
to true
so a rerender is triggered.
Subsequent clicks you change it from true
to true
which isn't a change, so it doesn't.
You could toggle it:
const [render, rerender] = useState(false);
and
rerender(!render);
so it actually changes.
… but this smells of being an XY Problem, and you should probably be changing something which is actually being rendered.