Top State management libs for React Native ✨
Tags: reactnative, redux, alternative, statemanagement
Published: 2024-06-22 14:49:52

### State Management in React Native: A Comprehensive Guide 

State management is a crucial aspect of developing robust and scalable React Native applications. It involves managing the state of your app, ensuring that your components reflect the correct data at all times. In this article, I'll explore various state management techniques in React Native, comparing different libraries and approaches to help you choose the best one for your needs.

#### Understanding State in React Native

In React Native, state refers to a data structure that determines how a component renders and behaves. State is mutable, meaning it can change over time, usually in response to user actions or network responses. Proper state management ensures that your app's UI updates correctly when the state changes.

### Built-in State Management

React Native provides a built-in way to manage state using the `useState` hook for functional components and `this.setState` for class components. This method is ideal for simple state management within individual components.

**Example using `useState`:**

```javascript
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';

const CounterApp = () => {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
};

export default CounterApp;
```

### Context API

For managing state across multiple components, React Native offers the Context API. It allows you to share state without passing props down manually through every level of the component tree.

**Example using Context API:**

```javascript
import React, { createContext, useState, useContext } from 'react';
import { View, Text, Button } from 'react-native';

const CountContext = createContext();

const CountProvider = ({ children }) => {
  const [count, setCount] = useState(0);
  return (
    <CountContext.Provider value={{ count, setCount }}>
      {children}
    </CountContext.Provider>
  );
};

const Counter = () => {
  const { count, setCount } = useContext(CountContext);
  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
};

const App = () => (
  <CountProvider>
    <Counter />
  </CountProvider>
);

export default App;
```

### Redux

Redux is a popular library for managing state in React and React Native applications. It provides a predictable state container and ensures that state changes are traceable and manageable. Redux is ideal for larger applications with complex state logic.

**Example using Redux:**

1. **Install Redux and React-Redux:**

```bash
npm install redux react-redux
```

2. **Create a Redux Store:**

```javascript
import { createStore } from 'redux';

const initialState = { count: 0 };

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

const store = createStore(reducer);
```

3. **Create React Components and Connect to Redux:**

```javascript
import React from 'react';
import { Provider, useDispatch, useSelector } from 'react-redux';
import { View, Text, Button } from 'react-native';
import store from './store'; // Import your store

const Counter = () => {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increment" onPress={() => dispatch({ type: 'INCREMENT' })} />
    </View>
  );
};

const App = () => (
  <Provider store={store}>
    <Counter />
  </Provider>
);

export default App;
```

### MobX

MobX is another state management library that uses observables to track state changes. It is known for its simplicity and flexibility, making it an excellent choice for developers who prefer a more straightforward approach than Redux.

**Example using MobX:**

1. **Install MobX and MobX-React:**

```bash
npm install mobx mobx-react
```

2. **Create a MobX Store:**

```javascript
import { observable, action } from 'mobx';

class CounterStore {
  @observable count = 0;

  @action increment = () => {
    this.count += 1;
  };
}

export default new CounterStore();
```

3. **Create React Components and Connect to MobX:**

```javascript
import React from 'react';
import { observer } from 'mobx-react';
import { View, Text, Button } from 'react-native';
import counterStore from './store'; // Import your store

const Counter = observer(() => (
  <View>
    <Text>{counterStore.count}</Text>
    <Button title="Increment" onPress={counterStore.increment} />
  </View>
));

const App = () => <Counter />;

export default App;
```

### Zustand

Zustand is a lightweight state management library that provides a more flexible and straightforward approach compared to Redux and MobX. It uses hooks for state management, making it very easy to integrate into React Native applications.

**Example using Zustand:**

1. **Install Zustand:**

```bash
npm install zustand
```

2. **Create a Zustand Store:**

```javascript
import create from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
}));

export default useStore;
```

3. **Create React Components and Use Zustand:**

```javascript
import React from 'react';
import { View, Text, Button } from 'react-native';
import useStore from './store'; // Import your Zustand store

const Counter = () => {
  const count = useStore((state) => state.count);
  const increment = useStore((state) => state.increment);

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increment" onPress={increment} />
    </View>
  );
};

const App = () => <Counter />;

export default App;
```

### Valtio

Valtio is another lightweight state management library that uses proxies to manage state. It provides a simple and reactive way to manage state in your React Native applications.

**Example using Valtio:**

1. **Install Valtio:**

```bash
npm install valtio
```

2. **Create a Valtio Store:**

```javascript
import { proxy, useSnapshot } from 'valtio';

const state = proxy({ count: 0 });

const increment = () => {
  state.count += 1;
};

export { state, increment };
```

3. **Create React Components and Use Valtio:**

```javascript
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useSnapshot } from 'valtio';
import { state, increment } from './store'; // Import your Valtio store

const Counter = () => {
  const snapshot = useSnapshot(state);

  return (
    <View>
      <Text>{snapshot.count}</Text>
      <Button title="Increment" onPress={increment} />
    </View>
  );
};

const App = () => <Counter />;

export default App;
```

### Conclusion

Choosing the right state management solution depends on the complexity and scale of your React Native application. For simple applications, the built-in state management and Context API are often sufficient. For larger applications with more complex state logic, Redux, MobX, Zustand, or Valtio can provide the necessary tools to manage state effectively.

By understanding and implementing the appropriate state management techniques, you can ensure your React Native application remains maintainable, scalable, and responsive to user interactions.

Valtio is my personal favourite for small or medium-sized apps.❤️

Manjot Singh,
Senior Mobile Engineer at Yara.com