React Native : Get to know Simple Zustand State Management
If you’ve never heard of Zustand but still wake up from night terrors with Redux as the main baddie, you should absolutely make friends with this jamming bear. It takes only THREE MINUTES to set up, is flexible and unopinionated, and is arguably the simplest to understand and use. So bear with me while I demonstrate how to utilize Zustand today.
What is an application state?
State is a piece of information that our software stores to reflect changes that take place while it is operating and during user interactions. Let’s look at what can really be kept in a state instead of giving another dull Wikipedia definition:
1. information about the logged-in user,
2. a list of products retrieved from the backend,
3. a flag indicating whether the navigation bar is open or closed,
4. and the total cost of all the items in the user’s shopping cart.
In React apps, we separate states into two categories.
Local State
State that is inextricably linked with a component that modifies the UI look. This state does not have to be shared by all components. A excellent example is flagging the navbar state from the list above. You don’t have to worry about sharing this information because the navigation bar is probably the only component that cares about it.
Global State
This state, on the other hand, contains data that may be used by numerous hierarchical components in your program.
What is Zustand?
Zustand is a state management created by designers Jotai and React-spring.
Zustand state management which is small, fast, and scalable using simplified flux principles. Have a convenient API based on hooks, not boilerplate or opinions.
Store.js
import create from 'zustand';
const initialState = {
firstName: 'John',
lastName: 'Snow',
};
// Log every time state is changed
const log = (config) => (set, get, api) =>
config(
(...args) => {
console.log(' applying', args);
set(...args);
console.log(' new state', get());
},
get,
api
);
const useStore = create(
log((set, get) => ({
...initialState,
setFirstName: (firstName) => set({ firstName }),
setLastName: (lastName) => set({ lastName }),
getLastName: () => {
const name = get().firstName;
console.log('name', name);
},
reset: () => {
set(initialState);
},
}))
);
export default useStore;
// const firstName = useStore((state) => state.firstName);
// const lastName = useStore((state) => state.lastName);
// const setFirstName = useStore((state) => state.setFirstName);
// const setLastName = useStore((state) => state.setLastName);
App.js
import * as React from 'react';
import { Text, View, StyleSheet, TextInput } from 'react-native';
import Constants from 'expo-constants';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import useStore from './store';
export default function App() {
const firstName = useStore((state) => state.firstName);
const lastName = useStore((state) => state.lastName);
const setFirstName = useStore((state) => state.setFirstName);
const setLastName = useStore((state) => state.setLastName);
return (
<View style={styles.container}>
<Text style={styles.title}>React Native Zustand Example</Text>
<Card style={styles.card}>
<View style={styles.form}>
<Text>Name</Text>
<TextInput
style={styles.input}
onChangeText={(val) => setFirstName(val)}
value={firstName}
/>
<TextInput
style={styles.input}
onChangeText={(val) => setLastName(val)}
value={lastName}
/>
</View>
<Text style={styles.result}>{`Result : ${firstName} ${lastName}`}</Text>
</Card>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
title: {
margin: 24,
marginTop: 0,
fontSize: 14,
fontWeight: 'bold',
textAlign: 'center',
},
card: {
alignItems: 'center',
justifyContent: 'center',
padding: 24,
},
form: {
flexDirection: 'row',
alignItems: 'center',
},
result: {
alignItems: 'center',
justifyContent: 'center',
paddingVertical: 24,
},
input: {
height: 40,
margin: 5,
borderWidth: 1,
padding: 10,
width: 100,
},
});
Snack Link : https://snack.expo.dev/@rudiahmad/react-native-zustand-sample