DEV Community

竺浩
竺浩

Posted on

Zustand: the benefit of a state management library

Introduction

States are essential to an frontend application. You want the states to contain important data for the frontend to render in real time. A naive approach is to define your states within components. You have to carefully orchestrate the component in which you define a certain state, otherwise you will have issues accessing them. To enable a state acceessible in multiple components, you will need to pass them as props, which can cause prop drilling, making the code hard to maintain. This is where state management libraries kicks in - they maintain states effectively and makes our life a lot easier. This Blog uses Zustand as an example to illustrate the benefit state mangement libraries brings.

How?

Zustand, like many other state management libraries, mainly serve this purpose: Define all states in one place, and any component can access any state.

Examples

  • Without Zustand, you can't have access to states neatly.
// Component A
const [nodes, setNodes] = useState([]);

// Component B - Can't access Component A's nodes! 😢
// Would need to pass through props (prop drilling)
Enter fullscreen mode Exit fullscreen mode
  • With the help of Zustand, We can have access to any states where we want.
// workflowStore.ts - Define once
export const useWorkflowStore = create({
  nodes: [],
  setNodes: (nodes) => set({ nodes })
});

// Component A
const { nodes, setNodes } = useWorkflowStore();

// Component B - Can access the SAME nodes! 🎉
const { nodes } = useWorkflowStore();
Enter fullscreen mode Exit fullscreen mode

Benefit Zustand provides

A brief summary here, Zustand offer the following key benefits

  • Any component can access state directly
  • No prop drilling (passing props through many layers)
  • State persists across component unmounts
  • Automatic re-renders when state changes

Top comments (0)