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
(oryarn 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>
);
}