0
0
React Nativemobile~5 mins

Zustand as lightweight alternative in React Native

Choose your learning style9 modes available
Introduction

Zustand helps you manage app data simply and fast without extra complexity.

You want to share data between screens without passing props everywhere.
Your app needs a small and easy way to remember user choices or settings.
You want to avoid complicated setup for state management.
You want a fast and simple tool that works well with React Native.
You want to keep your app code clean and easy to understand.
Syntax
React Native
import create from 'zustand'

const useStore = create(set => ({
  count: 0,
  increase: () => set(state => ({ count: state.count + 1 })),
  decrease: () => set(state => ({ count: state.count - 1 }))
}))

create makes a store to hold your app data.

Inside, you define state variables and functions to change them.

Examples
This store holds a name and a function to update it.
React Native
const useStore = create(set => ({
  name: 'Guest',
  setName: (newName) => set({ name: newName })
}))
This store manages a list of tasks and adds new ones.
React Native
const useStore = create(set => ({
  todos: [],
  addTodo: (todo) => set(state => ({ todos: [...state.todos, todo] }))
}))
Sample App

This React Native app shows a number and two buttons to add or subtract from it. Zustand keeps the number state simple and shared inside the app.

React Native
import React from 'react'
import { View, Text, Button } from 'react-native'
import create from 'zustand'

const useStore = create(set => ({
  count: 0,
  increase: () => set(state => ({ count: state.count + 1 })),
  decrease: () => set(state => ({ count: state.count - 1 }))
}))

export default function Counter() {
  const { count, increase, decrease } = useStore()

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text style={{ fontSize: 48, marginBottom: 20 }} accessibilityLabel="Current count">{count}</Text>
      <View style={{ flexDirection: 'row', gap: 20 }}>
        <Button title="-" onPress={decrease} accessibilityLabel="Decrease count" />
        <Button title="+" onPress={increase} accessibilityLabel="Increase count" />
      </View>
    </View>
  )
}
OutputSuccess
Important Notes

Zustand is very small and fast, so it won't slow your app.

You can use Zustand with React Native without extra setup like Redux.

Remember to keep your state simple and only store what you need.

Summary

Zustand is a simple tool to manage app data in React Native.

It uses a store with state and functions to update it.

It helps keep your app code clean and easy to maintain.