117. React Hooks implement forceUpdate

Hits: 0

If your [render] () method depends on some other data, you can tell the React component that it needs to be re-rendered by calling forceUpdate().
Calling forceUpdate() will cause the component to skip shouldComponentUpdate() and call render() directly. This will trigger the component’s normal [lifecycle] will cause the component to skip shouldComponentUpdate() and call render() directly. This will trigger the component’s normal [lifecycle] methods, including each child component’s shouldComponentUpdate() method.
forceUpdate is to re-render. Some variables are not in the state, and when you want to update the variable, refresh the render; or a variable in the state is too deep, and the render is not automatically triggered when it is updated. At these times, you can manually call forceUpdate to automatically trigger the render

useReducer

The base hooks useState and useReducer provide ways to refresh (update) functional components. Similarly, it is also a way to customize hook refresh. If you want a custom hook to refresh the function component, you can only use useState or useReducer in the custom component to force the refresh to achieve the effect similar to the previous forUpdate.

function useForceUpdate() {
  const [ , forceUpdateDispatch ] = useReducer(v => v + 1, 0)
  useEffect(() => {
    const unSubscribeFn = store.subscribe(() => {
      forceUpdateDispatch();
    })
    return unSubscribeFn;
  }, [ store ])
  return store;
}

When the data changes, forceUpdateDispatch will be called to change the flag, which will cause the reducer to change, trigger the custom hook useRedux change, and trigger the App to refresh in a chain to achieve the effect of the previous forceUpdate.

Leave a Reply

Your email address will not be published.