State Management in React Native with React Hooks and Context API

How do you manage state in a React application? Have you used Redux or Hookstate or MobX etc. to manage state in your last React application. Do you remember all the stuff like store, actions and reducers in Redux? And then all those connect, mapStateToProps and other functions to be able to access the state?

(Credit for this post goes to this post. Here in this post I am extracting the most minimal example for my own reference and for someone needs a ready to use code.)

As of 2019, React had already been equipped with all the necessary tools in its library to manage application state on its own. So all in all, you don’t need to install any external library for state management anymore.

According to this post, “This is beautiful example of synergy. Using Context API and Hooks together gives you very simple and ultimate global state management for your App.

I will show you the most simple implementation of the state management in react native with help of Context API and Hook. It is very simple and straight forward. I am using JSX syntax for this example.

Create state.jsx, initialState.js and reducer.js files somewhere within your app, with the following code, respectively.

state.jsx

import React, {createContext, useContext, useReducer} from 'react';
import reducer from './reducer'
const StateContext = createContext();
const StateProvider = ({reducer, initialState, children}) =>(
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);
const useStateValue = () => useContext(StateContext);

export {
  StateContext,
  StateProvider,
  useStateValue,
  initialState,
  reducer
}

reducer.js

const initialState = {
  user: { username: 'sholey1975' },
  theme: 'dark'
};
const reducer = (state, action) => {
    switch (action.type) {
      case 'setUser':
        return {
          ...state,
          user: action.payload
        };
    case 'changeTheme':
        return {
            ...state,
            theme: action.newTheme
        };
        
      default:
        return state;
    }
};

export {
  reducer,
  initialState
}

Now, in your App’s root file, include this state management tool to use like this:

import { StateProvider, initialState, reducer } from '@/src/state';

And wrap your mean return components like this:

return (
    <StateProvider initialState={initialState} reducer={reducer}>
    ...other component code here
    </StateProvider>
)

Now we are all setup to use and dispatch state from your App component. Let’s see how.

In some inner component call the useStateValue hook, which actually is a useContext hook to export your managed state and dispatch event.

import { useStateValue } from '@/src/state';

Initialise it inside the functional compoent:

const [{ theme, user }, dispatch] = useStateValue();

Now let’s first see the changing of our theme, using dispatch event.

<Text>Current Theme: {theme}</Text>
<Button onPress={() => dispatch({
    type: 'changeTheme',
    newTheme: theme == 'blue' ? 'white' : 'blue'
    })}><Text>Change theme</Text>
</Button>

Also, lets try to set our user:

React.useEffect(() => {
    if(id) {
        axios.get(`/url/to/get/userBy/${id}`)
        .then( u => {
            dispatch({
                type: 'setUser',
                payload: u
            })
        })
    }
}, [id])

So let’s check whether our new user is already in state value.

<Text>Hello ${user.username}</Text>

So using:

const [{ theme, user }, dispatch] = useStateValue();

In any App, component would reflect the change in theme, user or any other value stored in the state using this reducer and hook implementation using React Natives context Api and reducer hooks.

Conclusion:

Previous we used Redux and many other state management tools in our React applications. After 2019 with the stable version of context API and used Reducer hooks it is possible to manage state in your react application with just a few likes of code. You need to create a StateProvider and wrap your application code with it. You also create a reducer to update the saved state. This is very simple to manage state in React or React Native app without using any third party state management library.

Leave a Reply