Application State Management with React

Kent C. Dodds on how he uses React itself – and not something like Redux – for his Application State Management.

Here’s the real kicker, if you’re building an application with React, you already have a state management library installed in your application. You don’t even need to npm install (or yarn add) it. It costs no extra bytes for your users, it integrates with all React packages on npm, and it’s already well documented by the React team. It’s React itself.

React is a state management library.

The core React features driving his method is React’s revised context and Hooks.

// src/count/count-context.js
import React from 'react'
const CountContext = React.createContext();

function useCount() {
  const context = React.useContext(CountContext)
  if (!context) {
    throw new Error(`useCount must be used within a CountProvider`);
  }
  return context;
}

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

export {CountProvider, useCount}
// src/count/page.js
import React from 'react'
import {CountProvider, useCount} from './count-context'

function Counter() {
  const [count, setCount] = useCount();
  const increment = () => setCount(c => c + 1);
  return <button onClick={increment}>{count}</button>
}

function CountDisplay() {
  const [count] = useCount();
  return <div>The current counter count is {count}</div>
}

function CountPage() {
  return (
    <div>
      <CountProvider>
        <CountDisplay />
        <Counter />
      </CountProvider>
    </div>
  );
}

Application State Management with React →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.