Skip to main content

Persist onboarding state

Now we've used a state management library to store and edit the hasFinishedOnboarding, it's still not enough since it because it gets reset to the initial value whenever the app is restarted. Clearly, we need to persist the user state across app launches.

In the intro course, we used Async Storage to save and retrieve data. Good news is that state management libraries for React that also support React Native almost always have an adapter for Async Storage - persisting data across app launches is a very important feature for mobile apps!

Install Async Storage

npx expo install @react-native-async-storage/async-storage

Persist zustand state in Async Storage

Use the zustand persist middleware to persist using Async Storage:

Update: store/userStore.ts
@@ -1,18 +1,28 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
import { create } from "zustand";
+import { persist, createJSONStorage } from "zustand/middleware";

type UserState = {
hasFinishedOnboarding: boolean;
toggleHasOnboarded: () => void;
};

-export const useUserStore = create<UserState>((set) => ({
- hasFinishedOnboarding: false,
- toggleHasOnboarded: () => {
- return set((state) => {
- return {
- ...state,
- hasFinishedOnboarding: !state.hasFinishedOnboarding,
- };
- });
- },
-}));
+export const useUserStore = create(
+ persist<UserState>(
+ (set) => ({
+ hasFinishedOnboarding: false,
+ toggleHasOnboarded: () => {
+ return set((state) => {
+ return {
+ ...state,
+ hasFinishedOnboarding: !state.hasFinishedOnboarding,
+ };
+ });
+ },
+ }),
+ {
+ name: "plantly-user-store",
+ storage: createJSONStorage(() => AsyncStorage),
+ },
+ ),
+);

Now when the onboarding state gets set to true in the onboarding screen, reloading the app will take you straight in, instead of showing the onboarding screen again.

Checkpoint

AndroidiOS