Skip to main content

State Management

Overview

From React we already know that we use props to pass data from a parent to a child. Also, props are immutable. If a component needs to keep track of a piece of data over time, then it needs to use state. Every time the state changes, the component will rerender. So state is something mutable, as it changes over time. Also, state is private information and a component must manage it on its own. If you need to keep track of some kind of internal information that must not trigger a rerender then you should use useRef.

State Management

You can use exactly the same state management mechanism as in React. So usually I combine these hooks:

  • useState: simple component local state management
  • useReducer: redux-like state management, usually combined with useContext
  • useContext: used to move information from A to B or to provide operations on information
  • useRef: for internal (technical) state that must not trigger a rerender

If you are re redux fan than you can of course leverage the whole redux ecosystem.

useState

First you need to identify what piece of data is changing over time and give it a name (e.g. firstName). Then you must know the type of that data (e.g. string) and in the end you have to identify the initial value.

You can use the useState hook, just as you do in React when using functional components (see Counter Example below).

Counter Example

import React, {useState} from "react";
import { Button, Text, StyleSheet, View } from "react-native";

const CounterScreen = () => {
const [value, setValue] = useState(0);

return (
<View>
<Text style={styles.text}>Current Count: {value}</Text>

<Button
onPress={() => setValue(value + 1)}
title="Increment"
/>
<Button
onPress={() => setValue(value - 1)}
title="Decrement"
/>
</View>
)
};

const styles = StyleSheet.create({
text: {
fontSize: 30
}
});

export default CounterScreen;

useReducer + useContext

This is my favorite way of managing complex state and is already outlined here.