Search code examples
reactjsreact-nativelocal-storageasyncstoragezustand

How do I make zustand persist compatible with both web and React Native?


I'm writing a library which uses Zustand as its state management. One of the stores needs to be persistent. The library has to also be usable in both React and React Native.

Here's the main issue:

Using Zustand on the web with React sees the persist middleware use localstorage by default.

However, on React Native, AsyncStorage is the preferred alternative.

So how do I make my store compatible with both environments?


Solution

  • I apparently just need to learn how to read. It's in the docs:

    useMyCoolStore.persist.setOptions({
      storage: createJSONStorage(() => AsyncStorage),
    });
    

    This should be enough to set the storage type after the store is imported as a library.