State Management with React Hooks and Context API in 10 lines of code!

Ultimate and super simple Redux alternative for your App.

Luke Hall
<Simply />
Published in
7 min readJan 15, 2019

--

There are many ways how to handle global application state like Redux, MobX, etc. 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?

Now in 2019 I have a great news for you: You can forget about it!

Don’t take me wrong. Redux is a great library, it served it’s role for a long time, but it’s time to move forward. It’s just a technical evolution.

You don’t need to install any external library for state management anymore. Everything you need is available in React. And it’s damn easy to use.

State management in 10 lines of code?

Yes, you are reading it right. Just ten lines! But let’s take a look at two new React concepts first. Then I will introduce you the most simple state management ever.

React Context API

It’s actually not a new idea. Context API was part of React for long time, but only in experimental state.

Since React 16.3.0 it’s officially stable and ready to use in production.

The usage is pretty straightforward. Provider provides the value:

import React from 'react';const ThemeContext = React.createContext(
/* optional default value */
);
const App = props => (
<ThemeContext.Provider value={{ primaryColor: green }}>
{props.children}
</ThemeContext.Provider>
);

And Consumer allows to access the value (theme in this case) in any component of your App:

const ThemedButton = () => (
<ThemeContext.Consumer>
{value => (
<Button primaryColor={{ value.primaryColor }}>
I'm button using context!
</Button>
)}
</ThemeContext.Consumer>
);

There are other ways how to access context value like contextType in class based components as you will see below. For all the implementation details please check the official docs if you are interested.

--

--

Luke Hall
<Simply />

Senior JavaScript Developer • Keep things simple • medium.com/simply