Skip to main content

React useContext

React useContext

Best for slow moving / global data where a change would expect everything to redraw. For example

  • User Account Mangement
  • Changing a theme

For App Shells and Microfrontends, useContext is the best choice. Should only have small data footprint.

  • User
  • UserJWT
tip

Use useContextSelector if needing to manage high velocity state changes.

Use of State Managers best for teams where you need to have common standards. Easier for PR approval process to see acceptable patterns.

import { createContext } from "react";
import { useState } from "react";

const StoreContext = createContext();

const component = () => {
const data = useState({
name: "Ritesh",
email: "nyctonio.dev@gmail.com",
})[0];

const Child = () => {
return (
<div>
<StoreContext.Consumer>{(value) => <h1>name is {value.name}</h1>}</StoreContext.Consumer>
</div>
);
};

return (
<StoreContext.Provider value={data}>
<Child />
</StoreContext.Provider>
);
};

export default component;

Context

URLNotes
Mastering ContextGitHub
How to use React ContextArticle

Questions

At what point does context become a performance liability?

  • How many consumers can a single context support before re-renders matter?
  • When should you split one context into multiple narrow providers?
  • What breaks when you use context across a server/client component boundary?