UPDATE: 2019-02-12
This post would not work any more starting v16.8.0 as pointed out by Dimitar Nestorov in the comment section.
The official React Documentation Is there something like forceUpdate? discourages use of forceUpdate
.
Self note...
Today I learned you can use 2nd value in React Hooks method useState to emulate forceUpdate.
Donavon has shared a code snippet on Twitter on how to use React Hooks to emulate forceUpdate.
How does it work? `useForceUpdate` calls `useState` and returns the setter function. Whenever you call the setter, it force a re-render. The value (`undefined` in this case) doesn't need to change.
Strange, but it works. 🤷♂️14:23 PM - 08 Nov 2018
Donavon's twit on forceUpdate
Here is the copy/pastable code snippet.
Fork Donavon's code
Here is forceUpdate
in action.
Question?
I still can't figure out how calling useForceUpdate
is able to trigger the re-render as it is not updating any state.
Initially Donavon updated a dummy state but he found out it was unnecessary thus he isn't unsure how it's working, either.
@dance2die Me too, but just calling the setter returned by `useState` appears to be enough. Originally I WAS updating state, but it's not necessary.
const useForceUpdate = () => {
const [, setIt] = useState(false);
return () => setIt(it => !it);
};14:35 PM - 08 Nov 2018
More questions...
I tried to go thru the code in Chrome devtool but would require understanding React Fiber code to dig it.
Update
Asked the question in Reddit, https://www.reddit.com/r/reactjs/comments/9vgaso/
And /u/acemarke has kindly provided with an explanation.
Reply by /u/acemarke
https://www.reddit.com/r/reactjs/comments/9vgaso/how_does_2nd_value_in_react_hooks_usestates_able/e9by088/
Request for confirmation by rephrase
https://www.reddit.com/r/reactjs/comments/9vgaso/how_does_2nd_value_in_react_hooks_usestates_able/e9c261e/
Confirmation & additional remark
https://www.reddit.com/r/reactjs/comments/9vgaso/how_does_2nd_value_in_react_hooks_usestates_able/e9c6c27/
Articles to read
Photo by freestocks.org on Unsplash