Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forceUpdate with React hooks

Is there a replacement for forceUpdate that one can use with React hooks?

My use case is a shared state between component instances. Essentially each instance is just an view into single global state. With ES6 class the code register/unregister the component with the state in componentDidMount, the state calls forceUpdate on its changes and then the render method query the global state directly.

I consider to switch this to hooks. Initially useEffect seemed like a perfect match for the problem. But then I realized that I did not have access to forceUpdate.

I considered a workaround that called the useState hook to add a dummy counter and then updated the counter from the effect hook, but it felt like a hack. I can also copy all relevant shared state parameters into the component state in the effect hook and then refer to those from the state. But it essentially duplicates the state for no good bloating the code with lines that copy the state when currently I can just use those lines directly in the render method.

Update: Here is codesandbox.io link with shared state example that uses class components that I would like to convert to hooks without duplicating the state or using fake state updates.

like image 653
Igor Bukanov Avatar asked Dec 22 '22 21:12

Igor Bukanov


2 Answers

There is one other hack you can use to do a forceUpdate. Here it is:

Edit kind-hooks-rx2h4

From react docs:

Both useState and useReducer Hooks bail out of updates if the next value is the same as the previous one. Mutating state in place and calling setState will not cause a re-render. Normally, you shouldn’t mutate local state in React. However, as an escape hatch, you can use an incrementing counter to force a re-render even if the state has not changed.

like image 78
Praneeth Paruchuri Avatar answered Dec 26 '22 11:12

Praneeth Paruchuri


You can simply do this

You can simply add a dummy state that you can change to reliably initiate a re-render.

const [rerender, setRerender] = useState(false);

...
setRerender(!rerender); //whenever you want to re-render

And this will ensure a re-render of the component, since components always re-render on state change

like image 42
Abraham Avatar answered Dec 26 '22 12:12

Abraham