UNPKG

use-zustand

Version:

Another custom hook to use Zustand vanilla store

30 lines (29 loc) 1.03 kB
import { useEffect, useReducer } from 'react'; export function useZustand(store, selector, areEqual = Object.is) { const state = store.getState(); const [[sliceFromReducer, storeFromReducer], rerender] = useReducer((prev, fromSelf) => { if (fromSelf) { return fromSelf; } const nextState = store.getState(); if (Object.is(prev[2], nextState) && prev[1] === store) { return prev; } const nextSlice = selector(nextState); if (areEqual(prev[0], nextSlice) && prev[1] === store) { return prev; } return [nextSlice, store, nextState]; }, undefined, () => [selector(state), store, state]); useEffect(() => { const unsubscribe = store.subscribe(() => rerender()); rerender(); return unsubscribe; }, [store]); if (storeFromReducer !== store) { const slice = selector(state); rerender([slice, store, state]); return slice; } return sliceFromReducer; }