0

I have a state headerState that controls two UI elements: Mobile navbar and Auth dialog.

Mobile navbar and auth dialog both have properties isOpen, open and close

I need to come up with a flexible and extendible solution on how to structure the state.

I see several ways of solving this problem:

type NoArgsNoReturn = () => void;
// structure by category: navMenu and authDialog
type HeaderState = {
  navMenu: { isOpen: boolean; open: NoArgsNoReturn; close: NoArgsNoReturn },
  authDialog: { isOpen: boolean; open: NoArgsNoReturn; close: NoArgsNoReturn }
};

// structure by what they do
type HeaderState = {
  isOpen: { navMenu: boolean; authDialog: boolean },
  open: { navMenu: NoArgsNoReturn; authDialog: NoArgsNoReturn },
  close:{ navMenu: NoArgsNoReturn; authDialog: NoArgsNoReturn }
};

// separate states
type HeaderState = {
  isNavMenuOpen: boolean;
  isAuthDialogOpen: boolean;
  // if `open` is provided, isNavMenuOpen will be set to `open`, otherwise it will be toggled
  setNavMenuOpen: (open?: boolean) => void; 
  // same for `isAuthDialogOpen`
  setAuthDialogOpen: (open?: boolean) => void; 
}

But I can't figure out what would be the best way to structure it, there must be some best practices or practices developed from experience.

  • If this is React you might want the last one, as it'll be easier to update the state and use it. – kelsny May 05 '22 at 15:25
  • @catgirlkelly I'm using `zustand` for state management. In components I do `const { isOpen } = useHeaderState()` to retrieve state values so nested properties isn't an issue – PYTHON DEVELOPER999 May 05 '22 at 15:39
  • 1
    I would still use the last one because destructuring nested properties gets messy fast. – kelsny May 05 '22 at 15:41

0 Answers0