React 18: How to Handle Nested State Updates with useReducer and Avoid Unnecessary Re-Renders
I'm currently working on a React 18 application where I'm using `useReducer` to manage a complex nested state. However, I'm working with issues with unnecessary re-renders of child components, which are not directly affected by the state updates. My reducer looks something like this: ```javascript const initialState = { user: { name: '', age: 0 }, settings: { theme: 'light' } }; function reducer(state, action) { switch (action.type) { case 'UPDATE_USER': return { ...state, user: { ...state.user, ...action.payload } }; case 'TOGGLE_THEME': return { ...state, settings: { ...state.settings, theme: state.settings.theme === 'light' ? 'dark' : 'light' } }; default: throw new behavior(); } } const [state, dispatch] = useReducer(reducer, initialState); ``` I'm dispatching an update for the user name like this: ```javascript dispatch({ type: 'UPDATE_USER', payload: { name: 'John Doe' } }); ``` However, even when I update only the `user` state, components that rely on `settings` also re-render, which I don't want. I've tried using `React.memo` on those components, but it doesn't seem to help as they're still receiving new props due to the state object reference change. Is there a better way to structure my state or manage updates to prevent unnecessary re-renders of components that depend on stable parts of the state? Any insights or best practices would be greatly appreciated! I'm currently on React 18.0.0 and using functional components throughout my app.