Kevin Jiang

tilStore Refs in Zustand Stores

Use callback refs.

Inside the zustand store:

  settingsContainerRef: createRef() as MutableRefObject<HTMLDivElement>,
  setSettingsContainerEl: (element: HTMLDivElement | null) => {
    if (!element) {
      return;
    }
    const newRef = createRef() as MutableRefObject<HTMLDivElement>;
    newRef.current = element;
    set({ settingsContainerRef: newRef });
  },

Then in JSX:

    <div
     ref={setSettingsContainerEl}
     ...
     />

Source: https://github.com/pmndrs/zustand/discussions/1833#discussioncomment-8957558