You can also use a reducer function for this, so you dont have to spread the current state manually for each setPlayer call:
constinitialState={name:'Player',score:0,level:1,weapon:'Bow',arrows:20,}functionplayerReducer(currentState:typeofinitialState,nextState:Partial<typeofinitialState>){return{...currentState,...nextState}}functionPlayer(props:Partial<typeofinitialState>){constcombinedInitialState=useMemo(()=>({...initialState,...props}),[props])const[player,setPlayer]=useReducer(playerReducer,combinedInitialState)consthandleShootArrow=useCallback(()=>{setPlayer({// we dont have to spread the whole player object here// because the reducer already does that for usarrows:player.arrows-1,score:player.score+10})},[player])// ...}
You could also make the reducer more complex, for example you could do something like this:
You can also use a reducer function for this, so you dont have to spread the current state manually for each setPlayer call:
You could also make the reducer more complex, for example you could do something like this: