Home > Software design >  Can't update Zustand state using setState function
Can't update Zustand state using setState function

Time:09-26

In Comp1 when i hover mouse on it i want the state to change to true (I'm passing true param to it). Also i want to ensure that by doing so this will not cause the Comp2 component to re-render.

My understanding was that if i do like so useStoreOnHover.setState({ onComp1: true }) it should work but it does not :(

I have also tried with const onComp1Set = useStoreOnHover((s) => s.onComp1Set) but still same :(

The only way i was able to get it working is by const { onComp1Set } = useStoreOnHover() but I'm trying to avoid these type of de-structuring because it also triggers re-renders to other components.

Live example: https://codesandbox.io/s/winter-grass-qxrv8

import create, { GetState, SetState } from "zustand";

type typeStoreOnHover = {
  onComp1: boolean;
  onComp1Set: (val: boolean) => void;

  onComp2: boolean;
};

export const useStoreOnHover = create<typeStoreOnHover>(
  (set: SetState<typeStoreOnHover>, get: GetState<typeStoreOnHover>) => {
    return {
      onComp1: false,
      onComp1Set: (val) => set({ onComp1: val }),

      onComp2: false
    };
  }
);

const Comp1 = () => {
  const onComp1 = useStoreOnHover.getState().onComp1;
  // const onComp1Set = useStoreOnHover((s) => s.onComp1Set);

  console.log("Comp 1", onComp1);
  return (
    <div
      onMouseEnter={() => {
        // onComp1Set(true);
        useStoreOnHover.setState({ onComp1: true });
      }}
    >
      Comp 1 {onComp1 ? "True" : "False"}
    </div>
  );
};

const Comp2 = () => {
  const onComp2 = useStoreOnHover((s) => s.onComp2);

  console.log("Comp 2", onComp2);

  return <div>Comp 2 </div>;
};

export default function App() {
  return (
    <>
      <Comp1 />
      <Comp2 />
    </>
  );
}

CodePudding user response:

According to zustand documentation, this should be the actual approach,

const onComp1 = useStoreOnHover((s) => s.onComp1);

I have tested it on your CodeSandBox link and it worked.

I am not familiar with the zustand library but this might help you. Happy coding!

  • Related