React does not reflect state change when updating react-query cache with setQueryData

Please Note: The TotalFreedom Forum has now been put into a read-only mode. Total Freedom has now closed down and will not be returning in any way, shape or form. It has been a pleasure to lead this community and I wish you all the best for your futures.
  • Calling `setQueryData` on a socket event listener does not rerender components.

    I have a React project that uses react-query to manage query related logic. I am also using socket.io rooms for data updates. The client may subscribe to a room and receive update payloads for that specific resource.

    Code
    socket.on("DATA:consumable", (payload: { room: ""; data: unknown }) => {
      const room = payload.room.split(":"); // room: "type:id"
      const resourceType = room[0];
      const resourceId = room[1];
    
      queryClient.setQueryData([resourceType, resourceId], (old) => {
        // old is not touched
        return payload.data;
      });
    });

    In this event listener, I retrieve the `resourceType` and `resourceId`, call `setQueryData` with the appropriate query key, and return the payload data. I am not mutating the old state of this query.

    In these two component, I define `todo` as the react-query state (if defined) or the data provided by the todos component. When the data is updated in the above socket listener, I expect the cache to be set and the Todo component to reflect the updated state. In the react-query devtools I observe that the cache is properly set when new data is emitted.

    Replacing react-query cache with other stores correctly rerenders the Todo component.

    With redux:

    Code
    socket.on("DATA:consumable", (payload: { room: ""; data: unknown }) => {
      ...
    
      dispatch(setTestTodo(payload.data));
    });
    Code
    const Todo = ({ data }: { data: Todo }) => {
    
      const testTodoState = useSelector((state) => state.testTodo);
    
      const todo = testTodoState || data;
    
      return (
        ...
      );
    };

    Here the todo component correctly reflects state updates. Other questions about setQueryData not rerendering components are resolved by cloning the old cache in the updater callback rather than mutating the old cache state. I am updating my cache state immutably so this shouldn't be an issue.