1

I use react Hooks, especially useReducer. State changes, but functional component does not rerender. The drawer should be opened after pressing the button in the menu. State changes but drawer does not open.

This is sandbox witj code https://codesandbox.io/s/affectionate-cdn-o0e6u?file=/src/drawer/drawer.tsx

const Drawer: FC = () => {
  const [state, dispatch] = useReducer(serviceReducers, serviceState);

  const drawerClose = () => {
    dispatch({ type: ActionTypes.OPEN_DRAWER, payload: false });
  };

  const drawer = (
    <div>
      <IconButton onClick={drawerClose}>
        <CancelPresentationIcon />
      </IconButton>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod            
      </p>
    </div>
  );
  return (
    <nav>
      <Drawer
        anchor={"left"}
        open={state.drawer}
        onClose={drawerClose}
        ModalProps={{
          keepMounted: true
        }}
      >
        {drawer}
      </Drawer>
    </nav>
  );
};

And this is reducer

export enum ActionTypes {
  OPEN_DRAWER = "openDrawer"
}
export interface ServiceState {
  drawer: boolean;
}
interface OpenDrawer {
  type: ActionTypes.OPEN_DRAWER;
  payload: boolean;
}
export type ServiceActions = OpenDrawer;

export const serviceState = {
  drawer: false
};

export function serviceReducers(
  state: ServiceState,
  action: ServiceActions
): ServiceState {
  switch (action.type) {
    case ActionTypes.OPEN_DRAWER:
      return {
        ...state,
        drawer: action.payload
      };

    default:
      return state;
  }
}
Festina
  • 327
  • 3
  • 17

1 Answers1

-1

Here you need to use context API to https://reactjs.org/docs/context.html. useReducer() manages and manipulates the state for the individual component. You need to use the Props Drilling technique using Context API. using useReducer() you can not call other component useReducer() action. If you use redux then you should manage this with redux

Suhag Lapani
  • 655
  • 10
  • 18