I have setup a state in the context using a reducer
const playerStateReducer = ((state: PlayerState, action: PlayerAction) => {
switch (action.type) {
case "SET_LOCATION": {
return {...state, location: action.payload};
}
case "PICKUP_ITEM": {
return {...state, inventory: [...state.inventory, action.payload]};
}
default:
return state;
}
});
And then context Provder is setup as const GameStateProvider = (props: any) => { const [playerState, playerStateDispatch] = useReducer(playerStateReducer, initialPlayerState);
const values = {
playerState: playerState,
playerStateDispatcher: playerStateDispatch,
};
return (
<GameStateContext.Provider value={values}>{props.children}</GameStateContext.Provider>
);
}
I now have 2 memoized components. 1 for map and 1 for inventory. What i would like is that if player moves around, inventory is not re-rendered. And if something happens in inventory then map is not rerendered. Right now when player moves around, inventory component also gets re-rendered, even tho inventory has not changed.
const PlayerInventory = () => {
const {playerState} = useGameState();
return (
<div className={'inventory-container'}>
{playerState.inventory.map((item: IInventorySocket) => <InventoryItem item={item}/>)}
</div>
);
}
export default React.memo(PlayerInventory);
I understand this is because playerstate is updated so a totally new state causes the inventory component to re-render. What can i do to prevent unnessesary rerendering?