🐻 Zustand the JavaScript state handling library
Tags: typescript, react, frontend, zustand
Published: 2023-05-20 20:14:46

_**By Yamilka Cosme**_

Zustand is a library for managing states in React applications. Zustand is based on the Context API (yes, Zustand uses Context API to share data), allowing you to easily share and update state between application components. You can create a new store in Zustand using the createStore function. This function takes an object as an argument, which includes the initial state and the functions that update the store. 

**Why zusntand?**

1. **Reduced Boilerplate**, Zustand.js eliminates much of the boilerplate code required by Redux, allowing you to write more concise and readable code.

2. **Built-in React Integration**, Zustand.js is built with React in mind and seamlessly integrates with React's Context API, eliminating the need for additional libraries or boilerplate code.

3. **TypeScript Support**, Zustand.js provides excellent TypeScript support out of the box, making it easier to catch errors and enforce type safety in your application.

```javascript
import create from 'zustand';

const useMe = create((set) => ({
  data: {firstName: "", lastName: ""},
  updateMe: () => set((state) => ({ data:  {firstName: "coconut", lastName: "coconut"} })),
	clearMe: ()=> set((state) => ({ data:  {firstName: "", lastName: ""} })),
}));

```

---
**Accessing the Store**
---
To access the store, first import the hook we generated (in this case, **_useMe_**), and access the state through the function _((state)⇒ state)_.

```javascript
import useMe from './useMe.store.ts';

const Home = () => {

  const dataUser = useMe (state => state.data)

  return (
      <h1>UserName: {dataUser.firstName} </h1>
  )
}
export default Home

```

---
**Updating the state with the SET function**
---
To update the values we have in the store, we need to add functions that will perform this task. The functions can receive several props, one of them being set, which allows us to update the store. In this case, we have the function **_updateMe_** to update the **_firstName_** and _**lastName**_, and the function **_clearMe_** to reset the initial values in the store. The set property has a certain characteristic where we are not required to send the entire object every time, as long as it is linear.

```javascript
import create from 'zustand';

const useMe = create((set) => ({
  data: {firstName: "", lastName: ""},
  updateMe: () => set((state) => ({ data:  {firstName: "coco", lastName: "coco"}})),
	clearMe: ()=> set((state) => ({ data:  {firstName: "", lastName: ""} })),
}));

```

---
**Retrieving data from the store using the GET function within the same store**
---
The functions we create in the store are not always about updating data. Sometimes we need to perform actions or operations where we must use the data from the store (in this case, firstName and lastName). For such cases, we have the Get property that retrieves the current values from the store to be used in the function.

```javascript
import create from 'zustand';

const useMe = create((set) => ({
  data: {firstName: "coconut", lastName: "from the"},
  updateMe: () => set((state) => ({ data:  {...get.data, lastName: `${get.data.lastName} coconuts`} }))
}));
```

---
**_Accessing the store with shallow_**
---
When you are retrieving multiple data from the store, there may be a situation where one thing gets updated (e.g., firstName) while the others (e.g., lastName) remain the same. In this case, the application might mistakenly think that lastName has also changed because Zustand compares the entire object during the comparison process, rather than each individual element.

For such cases, we have the '_**shallow**_' property. This instructs Zustand to perform a shallow comparison instead of a strict one when the state is updated. In other words, it compares each value of the previous object with each property of the current object, rather than comparing the entire previous object with the new one. This is a crucial aspect of how Zustand introduces performance improvements in global state management.

```javascript
import useMe from './useMe.store.ts';

const Home = () => {

const { firstName, lastName } = useMe(
    (state) => ({ firstName: state.firstName, lastName: state.lastName }),
    shallow
  )

  return (
      <h1>UserName: {dataUser.firstName} {dataUser.firstName} </h1>
  )
}
export default Home
```

Did you like my post? 🤗 If so, react with ❤️ and comment below.

YamiYami says bye bye. 👋