Search code examples
reactjszustand

Having issue in using zustand to keep state updated


I am new to zustand and currently experienceing to build state by it.

In my app I have two component; one is parent, another one is child, which is wrapped by parent.

I have tried different way to create state in child. The result, however, is not as expected as the created state could not be updated in child.

Why is that?

App.js:

    import "./styles.css";
    import useCounterStore from "./hooks/useCounterStore";
    import Child from "./Child";
    export default function App() {
      const { count, add } = useCounterStore();
      return 

(
    <div>
      Parent
      <div className="childContainer">
        <Child name="child1"></Child>
        <Child name="child2"></Child>
      </div>
      <p>{count}</p>
      <button onClick={add}>Add</button>
    </div>
  );
}

Child.js:

import create from "zustand";
export default function Child(props) {
  const { name } = props;

  const { count, add } = create((set) => ({
    count: 1,
    add: () => set((state) => ({ count: state.count + 1 }))
  }))();

  return (
    <div className="child">
      <p>{name}</p>
      <p>{count}</p>
      <button onClick={add}>Add</button>
    </div>
  );
}

useCounterStore.js

 import create from "zustand";

const useCounterStore = create((set) => ({
  count: 1,
  add: () => set((state) => ({ count: state.count + 1 }))
}));

export default useCounterStore;

Child count always stay at 1

enter image description here


Solution

  • This is a answer from @RyanZeelie. It is worth posting it.

    useCounterStore() means you're calling the store that was created at app runtime. App starts, zustand creates the store. Your app loads. Now the store is created and can be accessed on any page by calling useCounterStore(). This is not going to create the store every time. It's already created. Calling create() at the component level is going to create a new store but since you're creating it in a component. Every time that component re renders

    Whenever a component re renders, you're not re rendering the entire app. Only specific components . So you're re rendering the child, and it's re creating all the functions in the child component, thus throwing out the store that was made at that level and creating it again.