Using React hooks to optimize re-renders
For global states, optimizing re-renders is important because not all components use all the properties in a global state. Let's learn how Zustand addresses this.
To use store
in React, we need a custom hook. Zustand's create
function creates a store
that can be used as a hook.
To follow the naming convention of React hooks, we have named the created value useStore
instead of store
:
// store.ts import create from "zustand"; export const useStore = create(() => ({ count: 0, text: "hello", }));
Next, we must use the created useStore
hook in React components. The useStore
hook, if it's invoked, returns the entire state
object, including all its properties. For example, let's define a component that shows the count
value in store
:
import { useStore } from "./store.ts"; const Component = () => { const { count, text } = useStore(); ...