Emulate forceUpdate with React Hooks

programming, react, selfnote, todayilearned


title: Emulate forceUpdate with React Hooks date: "2018-11-08" published_at: "2018-11-09T01:41:45.000Z" tags: "programming, react, selfnote, todayilearned" author: Sung M. Kim banner: ./images/featured-image.jpg

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.

Donavon's twit on forceUpdate

Here is the copy/pastable code snippet.

* No longer works
* Refer to https://sung.codes/blog/2018/11/08/emulate-forceupdate-with-react-hooks/
import React, { useState } from 'react';
const useForceUpdate = () => useState()[1];
const App = () => {
const forceUpdate = useForceUpdate();
return <button onClick={forceUpdate}>Click To Render</button>;
export default App;
view raw forceUpdate.js hosted with ❤ by GitHub

Fork Donavon's code

Here is forceUpdate in action.


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.

More questions...

I tried to go thru the code in Chrome devtool but would require understanding React Fiber code to dig it.


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

Request for confirmation by rephrase

Confirmation & additional remark

Articles to read

Photo by freestocks.org on Unsplash