这是用户在 2024-3-22 24:24 为 https://www.reactiive.io/articles/the-hidden-gems-of-react-native 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
The Hidden Gems of React Native Hero Image

The Hidden Gems of React Native
React Native 的隐藏宝石

Published on
| Minutes Read: 12 min
2024 年 3 月 8 日星期五 |阅读分钟数:12 分钟
Authors

Introduction 介绍

Recently, I read a book called "Zero to One: Notes on Startups, or How to Build the Future" written by Peter Thiel. At the beginning of the book, Peter Thiel starts with a question: "What important truth do very few people agree with you on?"
最近,我读了一本彼得·泰尔写的书,名叫《从零到一:创业笔记,或者如何构建未来》。在本书的开头,彼得·蒂尔以一个问题开始:“很少有人同意你的哪些重要真理?”

The problem he raises is that most people think that the future is going to be a slightly modified version of the present. Asking yourself this question is a good way to challenge this assumption and to think about what the future could be and how to build a very successful startup.
他提出的问题是,大多数人认为未来将是现在的一个稍微修改的版本。问自己这个问题是挑战这一假设并思考未来会怎样以及如何建立一家非常成功的初创公司的好方法。

Unfortunately, I'm very far from having the answer to this question in the context of startups, but I think I have some good answers in the context of React Native.
不幸的是,在初创公司的背景下我还远远没有找到这个问题的答案,但我认为在 React Native 的背景下我有一些很好的答案。

And that's what this article is all about.
这就是本文的全部内容。

State of React Native
React Native 的状态

To be honest, I was just trying to craft a catchy introduction. I don't have a secret truth about React Native that no one knows about.
老实说,我只是想写一个引人入胜的介绍。我没有关于 React Native 的秘密真相,没有人知道。

What I did was simply to look at the State of React Native (2023) and try to find some hidden gems that, apparently, are not so popular but can be very useful in some specific scenarios.
我所做的只是查看 React Native 的状态(2023),并尝试找到一些隐藏的宝石,这些宝石显然不那么受欢迎,但在某些特定场景中非常有用。

State of React Native is a survey made by Software Mansion and created by Bartłomiej Bukowski that is conducted every year to understand the current state of React Native. It's a great way to understand what the community is using and what the most popular libraries and tools are (and also the hidden gems).
React Native 的现状是由 Software Mansion 进行并由 Bartłomiej Bukowski 创建的一项调查,每年都会进行一次,以了解 React Native 的当前状态。这是了解社区正在使用什么以及最流行的库和工具(以及隐藏的宝石)的好方法。

TLDR; 太长了;

I know that you're busy and you don't have time to read the whole article. So here is a list of the hidden gems of React Native that I'm going to talk about:
我知道您很忙,没有时间阅读整篇文章。因此,这里列出了我将要讨论的 React Native 的隐藏宝石:

P.S: That's not a ranking.
PS:这不是排名。

About this article 关于本文

None of the libraries and tools that I'm going to talk about are sponsored. I'm just sharing my personal experience and my personal opinion about them.
我要谈论的库和工具都不是赞助的。我只是分享我的个人经历和对他们的个人看法。

However, you can sponsor my work by supporting me 😎
但是,您可以通过支持我来赞助我的工作😎

Join me on Patreon and be a part of the community 🎊
加入 Patreon,成为社区的一员 🎊

  • More than 50+ exclusive animations made with Reanimated, Gesture Handler and React Native Skia
    超过 50 个使用 Reanimated、Gesture Handler 和 React Native Skia 制作的独家动画
  • Get access to my newsletter and be the first to know about new content
    访问我的时事通讯并成为第一个了解新内容的人
  • Join a community of like-minded individuals passionate about React Native
    加入一个由志同道合、热衷于 React Native 的人组成的社区

Jotai: An atomic approach to State Management
Jotai:状态管理的原子方法

When filtering by the "State Management" category in the State of React Native, the usage percentage of Jotai is 14%. It's not a bad number, but it's not as popular as Redux, Redux Toolkit, or Zustand.
在React Native的State中按“State Management”类别筛选时,Jotai的使用比例为14%。这个数字还不错,但不像 Redux、Redux Toolkit 或 Zustand 那样受欢迎。

State of React Native - State Management

Jotai, created by Daishi Kato, is probably one of the most interesting libraries in the React ecosystem.
Jotai 由 Daishi Kato 创建,可能是 React 生态系统中最有趣的库之一。

Just to add a bit of context, Daishi is a React library author. He maintains three state management libraries: Zustand, Jotai, Valtio, and the React Server Components framework, Waku (sponsored by Vercel).
补充一点背景信息,Daishi 是一位 React 库作者。他维护着三个状态管理库:Zustand、Jotai、Valtio 和 React Server Components 框架 Waku(由 Vercel 赞助)。

When your mind tricks you into thinking that you're a great developer, just remember that there are people like Daishi 😅.
当您的大脑欺骗您认为自己是一名出色的开发人员时,请记住,还有像 Daishi 这样的人😅。

Why Jotai is so great?
为什么佐泰如此伟大?

I use Jotai in almost all of my projects, and I think it really shines when you need to manage complex state in a very simple way. The beauty of it is that it makes the idea of "Recoil atoms" lightweight and easy to use.
我几乎在所有项目中都使用了 Jotai,我认为当您需要以非常简单的方式管理复杂状态时,它确实会发挥作用。它的美妙之处在于它使“反冲原子”的想法变得轻量且易于使用。

The main concept of Jotai is the atom. An atom is a state that can be read and written. You can create an atom using the atom function, and then you can use the useAtom hook to read and write the state.
Jotai的主要概念是原子。原子是一种可以读写的状态。您可以使用 atom 函数创建一个原子,然后可以使用 useAtom 钩子来读取和写入状态。

P.S: For those aiming for a touch of cultural flair, "Jotai" translates to "State" in Japanese.
P.S:对于那些追求文化气息的人来说,“Jotai”在日语中翻译为“国家”。

import { atom, useAtom } from 'jotai'

const countAtom = atom(0)

function Counter() {
  const [count, setCount] = useAtom(countAtom)
  return (
    <View>
      <Text>{count}</Text>
      <TouchableOpacity onPress={() => setCount((c) => c + 1)}>increment</TouchableOpacity>
    </View>
  )
}

The useAtom hook returns the current value of the atom and a function to update it. When the atom is updated, the component is re-rendered.
useAtom 钩子返回原子的当前值和更新它的函数。当原子更新时,组件将重新渲染。

Atoms With Storage 原子与存储

I don't want to make this article too technical, but I think it's worth making an exception for the atomWithStorage function.
我不想让这篇文章过于技术化,但我认为值得为 atomWithStorage 函数破例。

Managing state persistence with React Native can be very tricky, especially when you need to manage the state of the app when it's closed and reopened. Jotai has a built-in function to handle this scenario.
使用 React Native 管理状态持久性可能非常棘手,特别是当您需要在应用程序关闭和重新打开时管理应用程序的状态时。 Jotai 有一个内置函数来处理这种情况。

What I really love is using this feature in combination with react-native-mmkv (which is also a bonus gem) to persist the state of the app in a very efficient way.
我真正喜欢的是将此功能与react-native-mmkv(这也是一个额外的宝石)结合使用,以非常有效的方式保留应用程序的状态。

To do that, I define a custom storage using react-native-mmkv, and then I create a helper function called createJotaiStorage that returns a storage object, which can be used with atomWithStorage.
为此,我使用 react-native-mmkv 定义自定义存储,然后创建一个名为 createJotaiStorage 的辅助函数,该函数返回一个存储对象,该对象可与 atomWithStorage 一起使用。

import { MMKV } from 'react-native-mmkv'

const storage = new MMKV({
  id: 'define.an.id',
})

const createJotaiStorage = <T>() =>
  createJSONStorage<T>(() => ({
    getItem: (key) => {
      return storage.getString(key) ?? null
    },
    setItem: (key, value) => storage.set(key, value),
    removeItem: (key) => storage.delete(key),
  }))

Then I can use the custom atomWithStorage function to create an atom that will be persisted in the storage.
然后我可以使用自定义 atomWithStorage 函数创建一个将持久保存在存储中的原子。

import { createJSONStorage, atomWithStorage as jotaiAtomWithStorage } from 'jotai/utils'

// Get On Init will ensure that the atom will be initialized with the value from the storage
// and it must be used in combination with React Suspense
export const defaultStorageOptions = {
  getOnInit: true,
}

export const atomWithStorage = <T>(key: string, initialValue: T) => {
  const storage = createJotaiStorage<T>()

  return jotaiAtomWithStorage<T>(key, initialValue, storage, defaultStorageOptions)
}

Learn more: Jotai Documentation
了解更多:Jotai 文档

Valtio: Proxy state made simple
Valtio:代理状态变得简单

Valtio is another state management library made by Daishi Kato. According to the State of React Native survey, Valtio appears in the "Other State Management" section with 9 votes, representing 9.7% of question respondents and 0.38% of survey respondents.
Valtio是加藤大师制作的另一个状态管理库。根据 React Native 的现状调查,Valtio 以 9 票出现在“其他状态管理”部分,占问题受访者的 9.7% 和调查受访者的 0.38%。

State of React Native - Other State Management

Since I already mentioned that I use Jotai in almost all of my projects, it's hard to believe that I also use Valtio. However, the truth is that I discovered Valtio recently, and the best definition of it is "pure magic".
由于我已经提到我在几乎所有项目中都使用 Jotai,所以很难相信我也使用 Valtio。然而事实是我最近发现了Valtio,对它最好的定义就是“纯粹的魔法”。

Here's an example of how to use Valtio:
以下是如何使用 Valtio 的示例:

import { proxy, useSnapshot } from 'valtio'

const state = proxy({ count: 0, text: 'hello' })

function Counter() {
  const snapshot = useSnapshot(state)
  return (
    <View>
      <Text>{snapshot.count}</Text>
      <TouchableOpacity onPress={() => state.count++}>increment</TouchableOpacity>
    </View>
  )
}

The proxy function creates a proxy object that can be used to store the state. The useSnapshot hook returns the current value of the proxy object, and it will re-render the component only when the used properties are updated. This means that in the example above, the "text" property will not trigger a re-render if it's updated from a different component.
proxy 函数创建一个可用于存储状态的代理对象。 useSnapshot 钩子返回代理对象的当前值,并且仅当使用的属性更新时才会重新渲染组件。这意味着在上面的示例中,如果“text”属性是从不同的组件更新的,则它不会触发重新渲染。

HOW IS THAT POSSIBLE? 🤯
这怎么可能? 🤯

I truly recommend the following articles to understand the magic behind Valtio:
我强烈推荐以下文章来了解 Valtio 背后的魔力:

Learn more: Valtio Documentation
了解更多:Valtio 文档

Shopify Restyle: Build a consistent, themed UI in minutes
Shopify Restyle:在几分钟内构建一致的主题 UI

The Restyle library offers a type-enforced system for constructing UI components in React Native with TypeScript. It's designed specifically for building UI libraries, with themability as its core focus.
Restyle 库提供了一个类型强制系统,用于使用 TypeScript 在 React Native 中构建 UI 组件。它专为构建 UI 库而设计,以主题能力为核心焦点。

In the State of React Native, Restyle boasts a usage percentage of 12%.
在 React Native 的状态中,Restyle 的使用比例为 12%。

State of React Native - Styling

I discovered this package a few years ago while following the React Native Fashion tutorial series by William Candillon (an additional bonus hidden gem).
几年前,我在关注 William Candillon 的 React Native Fashion 教程系列(额外的隐藏宝石)时发现了这个包。

The beauty of Restyle lies in its flexibility: you define the rules, the theme, the components, the variants, and then you can use them to build your UI.
Restyle 的美妙之处在于它的灵活性:您可以定义规则、主题、组件、变体,然后可以使用它们来构建您的 UI。

https://shopify.github.io/restyle/fundamentals/defining-your-theme
import { createTheme } from '@shopify/restyle'

const palette = {
  purpleLight: '#8C6FF7',
  purplePrimary: '#5A31F4',
  purpleDark: '#3F22AB',

  greenLight: '#56DCBA',
  greenPrimary: '#0ECD9D',
  greenDark: '#0A906E',

  black: '#0B0B0B',
  white: '#F0F2F3',
}

const theme = createTheme({
  colors: {
    mainBackground: palette.white,
    cardPrimaryBackground: palette.purplePrimary,
  },
  spacing: {
    s: 8,
    m: 16,
    l: 24,
    xl: 40,
  },
  textVariants: {
    header: {
      fontWeight: 'bold',
      fontSize: 34,
    },
    body: {
      fontSize: 16,
      lineHeight: 24,
    },
    defaults: {
      // We can define a default text variant here.
    },
  },
})

export type Theme = typeof theme
export default theme

Learn more: Restyle Documentation
了解更多:重新设计文档

Ignite (Infinite Red): The battle-tested React Native boilerplate
Ignite (Infinite Red):久经考验的 React Native 样板

Ignite is a React Native boilerplate created by Infinite Red. It's a great way to start a new project with a lot of features already set up.
Ignite 是由 Infinite Red 创建的 React Native 样板。这是开始一个已经设置了很多功能的新项目的好方法。

When I started working for my first company, I was introduced to Ignite by one of the senior developers. At the time, he suggested to initialize the project using the Redux Saga boilerplate (there really was an Ignite Redux Saga boilerplate at the time or my memory is failing me? 🤔 ).
当我开始在第一家公司工作时,一位高级开发人员向我介绍了 Ignite。当时,他建议使用 Redux Saga 样板来初始化项目(当时确实有一个 Ignite Redux Saga 样板,还是我记错了?🤔)。

The developer was really good from a technical perspective, but unfortunately, he was (just a bit) arrogant and I didn't trust him. So I started the project from scratch with the default React Native CLI.
从技术角度来看,开发人员确实非常出色,但不幸的是,他(只是有点)傲慢,我不信任他。因此,我使用默认的 React Native CLI 从头开始​​了该项目。

Fortunately, the beauty of life is that you are always in time to fix your mistakes. I rediscovered the Ignite CLI a few years later, and I've been using it a lot as my starting point for new projects.
幸运的是,生活的美妙之处在于你总是能及时纠正自己的错误。几年后,我重新发现了 Ignite CLI,并且经常使用它作为新项目的起点。

By checking the State of React Native, Ignite appears in the "React Native Tools" section with 12% usage. To be fair, they have 16k+ stars on GitHub and 1.5k+ forks, so I think that compared to the other hidden gems, Ignite is not so hidden 😅.
通过检查React Native的状态,Ignite出现在“React Native Tools”部分,使用率为12%。公平地说,他们在 GitHub 上有 16k+ 的 star 和 1.5k+ 的 fork,所以我认为与其他隐藏的宝石相比,Ignite 并没有那么隐藏😅。

State of React Native - React Native Tools

What I really love about Ignite is that all the best practices are already set up for you, and their stack is based on conservative choices that are battle-tested and proven to work.
我真正喜欢 Ignite 的一点是,所有最佳实践都已经为您设置好了,并且它们的堆栈基于经过实战测试并证明有效的保守选择。

Honestly, I love experimenting with things that really shouldn't be used in production, but when it comes to starting a new project, I think it's better to start with a solid foundation. Ignite is the perfect starting point for that.
老实说,我喜欢尝试那些不应该在生产中使用的东西,但是当谈到开始一个新项目时,我认为最好从坚实的基础开始。 Ignite 是一个完美的起点。

Learn more: Getting Started with Ignite & Ignite GitHub
了解更多:Ignite 入门和 Ignite GitHub

Maestro: The simplest and most effective mobile UI testing framework
Maestro:最简单、最有效的移动UI测试框架

Maestro is a mobile UI testing framework that allows you to write end-to-end tests in a simple and effective way.
Maestro 是一个移动 UI 测试框架,允许您以简单有效的方式编写端到端测试。

It was selected by 15% of the respondents in the State of React Native survey.
在 React Native 现状调查中,有 15% 的受访者选择了它。

State of React Native - React Native Tools

I discovered Maestro thanks to this outstanding App.js Conf talk by Henry Moulton: React Native end-to-end testing with Maestro.
我通过 Henry Moulton 的精彩 App.js Conf 演讲发现了 Maestro:使用 Maestro 进行 React Native 端到端测试。

Testing frameworks are usually complex and require a lot of setup. The philosophy behind Maestro is to make the testing process as simple as possible. Testing shouldn't be harder than writing the app itself.
测试框架通常很复杂并且需要大量设置。 Maestro 背后的理念是让测试过程尽可能简单。测试不应该比编写应用程序本身更困难。

The best way to visualize the power of Maestro is to see it in action. Here's an example taken from the official documentation.
体现 Maestro 力量的最佳方式就是亲眼目睹它的实际应用。这是来自官方文档的示例。

Maestro Demo

The magical part is that the end-to-end tests are basically independent from the app. You can even write the tests before the app is built, and then you can use them to drive the development of the app.
神奇的是,端到端测试基本上独立于应用程序。您甚至可以在构建应用程序之前编写测试,然后可以使用它们来驱动应用程序的开发。

Learn more: Maestro Documentation
了解更多:Maestro 文档

Conclusion 结论

I hope you found this article useful and that you discovered some new hidden gems of React Native. I'm sure there are many other hidden gems that I didn't mention in this article.
我希望您觉得这篇文章有用,并且您发现了 React Native 的一些新的隐藏宝石。我确信还有许多其他隐藏的宝石我在本文中没有提及。

My goal was to share my personal experience and opinion about these libraries and tools. I hope you found it helpful and that you will consider using them in your next projects.
我的目标是分享我对这些库和工具的个人经验和看法。我希望您发现它很有帮助,并且您会考虑在下一个项目中使用它们。

Drag to outliner or Upload
Close 关闭