Children components are not re rendered on forceUpdate() in React

Viewed 44

I have a callback method that calls a forceUpdate() hook in parent. I expect this to re render and call ChildA with updated props. These values are updated in another component say ChildB.

While I keep a debugger at callback method, I see updated values for props and Im getting a hit to return method as well. But the child component is not getting hit at all.

const Body = FC =>{
  const [state, setState] = useState<any>();

  const forceUpdate = useForceUpdate();
  const update = useCallback(() => forceUpdate(), []);

  return (
    //able to see updated state here when update() is called
    //but execution is not going inside ChildA
    //even use effects on updated state are not getting triggered
    <ChildA
       state = {state}
    />
    <ChildB
       update = {update}
    />
  )
}

Existing hook:

const reducer = (state: boolean, _action: null): boolean => !state;

export const useForceUpdate = () => {
    const [, dispatch] = useReducer(reducer, true);

    // Turn dispatch(required_parameter) into dispatch().
    const memoizedDispatch = useMemo(
        () => () => {
            dispatch(null);
        },
        [dispatch]
    );
    return memoizedDispatch;
};
1 Answers

When I changed the existing hook into the below format, this worked for me.

function useForceUpdate() {
        const [, forceUpdate] = useReducer(x => x + 1, 0);
        const memoizedUpdate = useMemo(
            () => () => {
                forceUpdate(0);
            },
            [forceUpdate]
        );
        return memoizedUpdate;
    };
Related