DEV Community

Cover image for State Management with Zustand
Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on

State Management with Zustand

Heya again!

As we all know state management can be challenging, especially when we have parent with nested children and passing props down from a parent component to children..and normally in the past I would use context from React together with a provider..but it happened that somewhere in the middle between the children the state wasn't updating correctly. So I was looking around for an alternative and came across with zustand

I was working on a table with some user information and a sidebar that shows the information of the user that you click, as in picture below.

Image description

So I created a store:




import { create } from 'zustand'

type User = {
  id: string
  name: string
  address: string
  emailAddress: string
}

type UsersStore = {
  selectedUser: Applicant | null
  handleOnClick: (user: User) => void
}


export const useUsersStore = create<UsersStore>((set) => ({
  selectedUser: null,
  handleOnClick: (user) => set({ selectedUser: user }),
}))



Enter fullscreen mode Exit fullscreen mode

Then on the child component user I just retrieve the value that I needed.




type UserProps = {
  user: UserModel
}

export default function UserProfile({ user }: UserProps) {
  const { handleOnClick } = useUsersStore()

  return (
    <TableRow
      key={user.id}
      className="cursor-pointer"
      onClick={() =>
        handleOnClick({
          id: user.id,
          name: user.name,
          address: user.address,
          emailAddress: user.emailAddress,
        })
      }
    >



Enter fullscreen mode Exit fullscreen mode

Then on the sidebar I retrieve the user object.




export default function UserProfileSidebar() {
  const { selectedUser } = useUsersStore()

  return (
    <div className="flex flex-col" id={selectedUser?.id}>



Enter fullscreen mode Exit fullscreen mode

Now when I click a user's row I can see the users details on the sidebar on the right.

Of course on the parent component i just pass the user object such as:




 {usersData.map((applicant) => (
                <UserProfile key={user.id} user={user} />
              ))}



Enter fullscreen mode Exit fullscreen mode

In the case you can just retrieve the value you need from the store and you wont have to worry about passing props between components plus is safer, easier and less costly.

Top comments (0)