首页/文章/react native

Universal Persisted Storage for React Native Expo + Next.js SSR — Herdi Tr.

2024-07-09
311011 分钟
...

The world of web development is marked by constant innovation, and developers are always on the lookout for tools and libraries that can simplify their workflows and make cross-platform development more efficient. In this article, we'll explore a powerful combination of technologies: React Native Expo, Next.js Server-Side Rendering (SSR), and some handy libraries like Fernando Rojo's Solito and Zustand with Persist Middleware. Together, these technologies enable the creation of cross-platform applications with universal storage capabilities.

Bridging the Gap with Solito

At the heart of this cross-platform development approach is Solito, a library created by Fernando Rojo. Solito acts as the missing link that seamlessly bridges the gap between React Native and Next.js, enabling developers to build powerful cross-platform applications. It serves two primary purposes:

  1. Navigation Simplified: Solito provides a tiny wrapper around React Navigation and Next.js, making it easy to share navigation code between native and web platforms. This means you can define your navigation logic once and use it across both platforms.
  2. Patterns and Examples: Solito offers a set of patterns and examples that guide developers in building cross-platform apps with React Native and Next.js. It simplifies the development process by providing best practices and clear examples.

Zustand with Persist Middleware

A crucial aspect of cross-platform development is managing state effectively. To achieve this, we turn to Zustand, a state management library. Zustand, when coupled with the Persist Middleware, enables us to persist and manage application state consistently across platforms.

Creating a Starter Project

To kickstart your journey into universal storage for React Native Expo + Next.js SSR, you can follow the guide provided by Solito: Solito Starter Project. This guide will help you set up the foundational structure of your project.

Universal Persisted Storage Implementation

In the /packages/app/storage.ts file, we implement persist storage that utilizes cookies for Next.js/web and React Native MMKV on the native side. This setup allows your data to be accessible on the server side and in React Native:

import Cookies from 'js-cookie'
import { compressToEncodedURIComponent, decompressFromEncodedURIComponent } from 'lz-string'
import { Platform } from 'react-native'
import { MMKV } from 'react-native-mmkv'
import { createJSONStorage, StateStorage } from 'zustand/middleware'
const mmkv = new MMKV()
const MMKVStorage: StateStorage = { 
  getItem: (name) => { 
    const value = mmkv.getString(name)
    if (!value)
      return null 
    return value 
  }, 
  setItem: (name, value) => { 
    mmkv.set(name, value) 
  },
  removeItem: (name) => { 
    mmkv.delete(name)
  },
}
const CookieStorage: StateStorage = { 
  getItem: (key) => { 
    const value = Cookies.get(key) 
    if (!value) return null 
    return decompressFromEncodedURIComponent(value) 
  }, 
  setItem: (key, value) => {
    Cookies.set(key, compressToEncodedURIComponent(value)) 
  }, 
  removeItem: (key) => { Cookies.remove(key) },
}
export const storage = { 
  create: <T>() => { 
    return createJSONStorage<T>(() => { 
      if (Platform.OS !== 'web')
      return MMKVStorage return CookieStorage 
    }) 
  },
}

Zustand Store

We create a Zustand store in /packages/app/stores/main.ts, where we define the state we want to persist. In this example, we're persisting the disableParallaxEffect key:

import { create } from 'zustand'
import { persist } from 'zustand/middleware'

import { storage } from './storage'
export namespace Main { 
  export type State = { 
    webHeaderHeight: number disableParallaxEffect: boolean
  }
}
export const main = create<Main.State>()( 
  persist( (set, get) => ({ 
    webHeaderHeight: 0, 
    disableParallaxEffect: false,
  }),
          { name: 'main-storage', 
           storage: storage.create(), 
           partialize: (state) => ({ disableParallaxEffect: state.disableParallaxEffect, }),
          }
         )
)

Addressing Hydration Mismatches

A challenge when persisting state in Next.js SSR is dealing with hydration mismatches. To address this issue, we make adjustments in the /apps/next/pages/_app.tsx file. This code ensures that the persisted state is correctly restored during server-side rendering:

App.getInitialProps = async (app: AppContext) => { const appProps = await NextApp.getInitialProps(app) const { req } = app.ctx if (req) { // if we're on the server const cookieStrings = req.headers.cookie || '' const cookies = Object.fromEntries( cookieStrings.split('; ')?.map((v) => v.split(/=(.*)/s)?.map(decodeURIComponent)) ) // Get and parse persisted main-storage cookie const mainStorageCookie = cookies['main-storage'] const mainStorage = JSON.parse( mainStorageCookie ? decompressFromEncodedURIComponent(mainStorageCookie) : `{"state":{"disableParallaxEffect":false},"version":0}` ) as { state: { disableParallaxEffect: boolean } version: number } if (mainStorage.state) { // Set main state main.setState(mainStorage.state) } } return { ...appProps }}

In this article, we've explored the fascinating world of universal storage for React Native Expo + Next.js SSR. By leveraging libraries like Solito, Zustand, and Persist Middleware, we can build cross-platform applications with shared state management, ensuring a consistent user experience across web and native platforms. The journey into cross-platform development continues to evolve, and these tools and patterns empower developers to tackle the challenges that come their way.

Feel free to explore and experiment with these technologies to enhance your cross-platform development projects. As always, stay curious and keep pushing the boundaries of what you can achieve in the world of web and mobile app development.

如果您觉得这篇文章有帮助,请点个赞吧~

分享文章

相关文章

更多文章 →
react native2024-09-10
使用Expo开发App解决消息推送问题(iOS,Android)
在上篇文章中,我们基于expo搭建了App的基础框架。在现代移动应用中,消息推送功能是提升用户体验的重要组成部分。本文将指导你如何在Expo环境中实现消息推送的功能,包含iOS与Android,以帮助你的用户及时接收到重要信息。 什么是Expo? Expo是一个开源平台,可帮助开发者轻松构建和部署React Native应用。它提供了许多工具和服务,简化了应用开发流程,尤其是在处理消息推送方面。 准备工作 在开始之前,确保你已经完成如下...
学习
react native2024-08-22
Mac 使用Charles进行手机https抓包
前言 还不知道怎么用手机连内网地址进行测试? 还不知道怎么用Charles抓手机HTTPS的包? 希望下面会对你有些帮助。 操作指南 操作环境: 电脑系统:Mac OS 手机系统:iOS 12及以上/Android Charles版本:V4.5.6 第一步:安装Charles证书到Mac 1.启动Charles,选择Help SSL Proxying→Install Charles Root Certificate image.png...
学习
react native2024-08-22
MacOS下抓取APP的数据包
已于 2024 05 31 16:56:15 修改 于 2024 05 31 16:32:42 首次发布 版权声明:本文为博主原创文章,遵循 版权协议,转载请附上原文出处链接和本声明。 1\. 准备工具 Charles:一款网络抓包工具,它支持HTTP和 的监控。您可以使用Charles来查看应用程序发送和接收的所有数据。 :Proxifier是一个代理软件,方便给没有设置代理的APP设置代理。 Charles 可以直接在 下载安装,可...
学习
react native2024-08-19
React Native 版本升级从0.72到0.75
前言 从2023年6月22日React Native官方发布0.72.0至今,一年多的时间React Native官方已经陆续发布了0.73、0.74、0.75三个版本,故决定对公司项目做版本升级,以获得更好的性能和稳定性。 我们先看下这三个版本,带来了哪些新功能、新特性: React Native 0.73 新的调试器 :增加了新的调试器,弃用旧版flipper调试工具,让调试过程更加高效顺畅。 稳定的符号链接支持: 简化您的开发工作...
学习
react native2024-05-08
用expo开发react native实在是太爽了
expo出来已经有一段时间了,发现相关的文章还是比较少的。如果你在开发react native,那么我推荐你赶快使用expo来开发把! 一、零配置开发,降低开发者的心智负担。如果你之前开发过react native,那么你肯定会遇到要配置java,sdk等一大堆东西,并且版本还要对应上,否则开发不了。甚至说新手也会被这些东西劝退。使用expo后,无需配置这些开发环境,像开发web一样流畅的开发react native。 二、实时真机调试...
学习
AI2026-09-01
Deep Agents 01:何为 Agent Harness,以及如何开始
1、本篇任务:完成一份多步骤、带证据的技术调研 普通客服 Agent 的问题短、工具少、输出即时。技术调研或编码任务会持续很久,产生计划、搜索结果、文件和中间结论。Deep Agents 在 LangChain/LangGraph 之上预装规划、虚拟文件系统、上下文压缩和子 Agent,适合这类开放任务。 本课让 Agent 比较两种向量数据库,并交付一份可验证报告。 2、什么时候需要 Deep Agent 满足以下两项以上再考虑:任务...
学习

评论

请登录后发表评论

去登录
加载评论中...

目录