Imagine you’re building a simple shopping website. You have a product page where users can add items to their cart, and a header that displays the number of items in the cart. Sounds simple, right? But here’s the challenge: how does the header know when someone adds an item on a completely different part of the page?
This is the shared state problem, which occurs when different parts of your application need to access and update the same information. In small apps, this isn’t a big deal. But as your app grows, managing shared state becomes one of the most complex and frustrating parts of React development.
In this handbook, you’ll learn:
-
What props and prop drilling are, and why they become problematic
-
How to recognize when you have a shared state problem
-
Multiple solutions to manage shared state effectively
-
When to use each solution
-
How to avoid common mistakes that even experienced developers make
By the end, you’ll understand how to build React applications that stay organized and maintainable as they grow.
What we’ll cover:
-
Prerequisites: What You Should Know Before Reading This Guide
Prerequisites: What You Should Know Before Reading This Guide
Essential React Knowledge
React Fundamentals (Required)
-
Functional components: You should be comfortable writing and using React functional components
-
JSX syntax: Understanding how to write JSX, use curly braces for JavaScript expressions, and handle events
-
Basic props: Know how to pass and receive props between parent and child components
-
useState hook: You should understand how
useState
works, including state updates and re-renders
<span class="hljs-comment">// You should be comfortable with code like this:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params">{ title }</span>) </span>{
<span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h1</span>></span>{title}<span class="hljs-tag"></<span class="hljs-name">h1</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Count: {count}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setCount(count + 1)}>
Increment
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
useEffect Hook (Recommended)
-
Basic understanding of side effects in React
-
When and why to use
useEffect
-
How dependency arrays work
-
This helps with understanding performance optimization sections
JavaScript Prerequisites
ES6+ Features (Required)
-
Arrow Functions:
const myFunc = () => {}
-
Destructuring:
const { name, age } = person
andconst [first, second] = array
-
Spread Operator:
...array
and...object
-
Template Literals: Using backticks and
${variable}
syntax -
Array methods:
map()
,filter()
,find()
,reduce()
– these appear frequently in state updates
<span class="hljs-comment">// You should understand this syntax:</span>
<span class="hljs-keyword">const</span> newItems = [...existingItems, newItem];
<span class="hljs-keyword">const</span> { name, price } = product;
<span class="hljs-keyword">const</span> updatedItems = items.map(<span class="hljs-function"><span class="hljs-params">item</span> =></span>
item.id === productId ? { ...item, <span class="hljs-attr">quantity</span>: item.quantity + <span class="hljs-number">1</span> } : item
);
Asynchronous JavaScript (Helpful)
-
Promises and async/await: For understanding API calls in state management
-
Basic error handling: try/catch blocks
Objects and Arrays (Required)
-
How to create, modify, and access nested objects and arrays
-
Understanding reference vs. value equality
-
Why direct mutation is problematic in React
React Concepts You’ll Encounter
Component Hierarchy (Required)
-
How parent and child components relate
-
Data flow from parent to child
-
Why data can’t easily flow “sideways” between sibling components
Re-rendering Behavior (Important)
-
When React components re-render
-
Why changing state causes re-renders
-
Basic understanding that creating new objects/functions causes re-renders
Event Handling (Required)
<span class="hljs-comment">// You should be comfortable with:</span>
<button onClick={<span class="hljs-function">() =></span> handleClick(item.id)}>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setValue(e.target.value)} /></span>
Development Environment
Tools You Should Have
-
React DevTools: Browser extension for debugging React components
-
Code editor: VS Code, WebStorm, or similar with React syntax highlighting
-
Node.js and npm/yarn: For installing packages mentioned in examples
Helpful but Not Required
-
TypeScript basics: Some examples mention TypeScript benefits
-
Testing knowledge: The testing section assumes some familiarity with Jest/React Testing Library
-
Build tools: Basic understanding of Create React App or Vite
Conceptual Understanding
Why State Management Matters
You should have experienced or understand these pain points:
-
Passing data through multiple component levels
-
Keeping data synchronized across different parts of your app
-
Managing complex application state
Basic Performance Awareness
-
Understanding that unnecessary re-renders can slow down apps
-
Awareness that some operations are more expensive than others
What You DON’T Need to Know
Advanced React Patterns
-
Higher-Order Components (HOCs)
-
Render props (though we explain them in the article)
-
Class components or lifecycle methods
-
Advanced hooks like
useLayoutEffect
oruseImperativeHandle
Complex State Management
- You don’t need prior experience with Redux, Context API, or other state libraries. I’ll explain everything from scratch
Advanced JavaScript
-
Closures, prototypes, or advanced functional programming concepts
-
Complex async patterns beyond basic promises
Self-Assessment Questions
Before diving in, ask yourself:
-
Can I build a simple React app with multiple components?
-
Do I understand how to pass data from parent to child via props?
-
Can I handle form inputs with useState?
-
Do I know when a React component re-renders?
-
Am I comfortable with array methods like map() and filter()?
If you answered “yes” to most of these, you’re ready for this handbook!
Recommended Preparation
If you need to brush up on React basics:
-
Complete the official React tutorial (tic-tac-toe game)
-
Build a simple todo app with local state
-
Practice passing props between components
If you need JavaScript review:
-
Practice array destructuring and spread syntax
-
Review arrow functions and array methods
-
Get comfortable with async/await
Quick warm-up exercise: Try building a simple counter app where:
-
Parent component holds the count state
-
Multiple child components display or modify the count
-
You’ll quickly see why prop drilling becomes a problem!
What This Guide Will Teach You
By the end, you’ll understand:
-
Why and when shared state becomes complex
-
How to solve prop drilling with Context API
-
When to use Redux, Zustand, or other state libraries
-
How to optimize performance with shared state
-
Testing strategies for state management
-
Best practices for maintainable code
The guide is designed to take you from “I know basic React” to “I can architect state management for complex applications” with plenty of examples and explanations along the way.
Understanding the Building Blocks: Props in React
Before we get into complex state management, let’s understand the fundamentals.
What are props?
Props (short for “properties”) are how React components communicate with each other. Think of props like passing notes between classrooms in a school – they carry information from one component to another.
<span class="hljs-comment">// This is a simple component that displays a person's information</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PersonCard</span>(<span class="hljs-params">props</span>) </span>{
<span class="hljs-comment">// props is an object containing all the data passed to this component</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"person-card"</span>></span>
{/* We access the data using props.propertyName */}
<span class="hljs-tag"><<span class="hljs-name">h2</span>></span>{props.name}<span class="hljs-tag"></<span class="hljs-name">h2</span>></span> {/* Shows the person's name */}
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Age: {props.age}<span class="hljs-tag"></<span class="hljs-name">p</span>></span> {/* Shows the person's age */}
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Job: {props.job}<span class="hljs-tag"></<span class="hljs-name">p</span>></span> {/* Shows the person's job */}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// This is how we USE the PersonCard component and pass it props</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
{/*
We're creating a PersonCard component and passing it three props:
- name: "Sarah"
- age: 28
- job: "Developer"
*/}
<span class="hljs-tag"><<span class="hljs-name">PersonCard</span>
<span class="hljs-attr">name</span>=<span class="hljs-string">"Sarah"</span>
<span class="hljs-attr">age</span>=<span class="hljs-string">{28}</span>
<span class="hljs-attr">job</span>=<span class="hljs-string">"Developer"</span>
/></span>
{/* We can create another PersonCard with different props */}
<span class="hljs-tag"><<span class="hljs-name">PersonCard</span>
<span class="hljs-attr">name</span>=<span class="hljs-string">"Mike"</span>
<span class="hljs-attr">age</span>=<span class="hljs-string">{35}</span>
<span class="hljs-attr">job</span>=<span class="hljs-string">"Designer"</span>
/></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Let’s break down what’s happening:
-
PersonCard is a function that receives
props
as its parameter -
props
is a JavaScript object containing all the data we passed:{name: "Sarah", age: 28, job: "Developer"}
-
We access individual pieces of data using dot notation:
props.name
,props.age
,props.job
-
The curly braces
{}
tell React “this is JavaScript code, not regular text” -
When we use
<PersonCard name="Sarah" age={28} job="Developer" />
, React automatically creates the props object
A more modern way: Destructuring props
Instead of writing props.name
every time, we can use destructuring to extract the values directly:
<span class="hljs-comment">// Instead of this:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PersonCard</span>(<span class="hljs-params">props</span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"person-card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h2</span>></span>{props.name}<span class="hljs-tag"></<span class="hljs-name">h2</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Age: {props.age}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Job: {props.job}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// We can write this (destructuring the props object):</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">PersonCard</span>(<span class="hljs-params">{ name, age, job }</span>) </span>{
<span class="hljs-comment">// JavaScript destructuring extracts name, age, and job from the props object</span>
<span class="hljs-comment">// It's like saying: "Take the props object and create separate variables"</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"person-card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h2</span>></span>{name}<span class="hljs-tag"></<span class="hljs-name">h2</span>></span> {/* No need for props.name anymore */}
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Age: {age}<span class="hljs-tag"></<span class="hljs-name">p</span>></span> {/* Just use the variable directly */}
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Job: {job}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
What destructuring does:
-
{ name, age, job }
tells JavaScript: “Extract thename
,age
, andjob
properties from the props object” -
It creates separate variables with those names
-
This makes our code cleaner and easier to read
What is Prop Drilling and Why is it a Problem?
Prop drilling happens when you need to pass data through multiple layers of components, even when the middle components don’t use that data. It’s like playing telephone through several people who don’t care about the message.
A simple example: Passing a username
<span class="hljs-comment">// Let's say we want to show a user's name in a deeply nested component</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> userName = <span class="hljs-string">"Alice"</span>; <span class="hljs-comment">// This data starts here at the top</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h1</span>></span>My Shopping App<span class="hljs-tag"></<span class="hljs-name">h1</span>></span>
{/* We pass userName down to Header */}
<span class="hljs-tag"><<span class="hljs-name">Header</span> <span class="hljs-attr">userName</span>=<span class="hljs-string">{userName}</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ userName }</span>) </span>{
<span class="hljs-comment">// Header receives userName but doesn't actually display it</span>
<span class="hljs-comment">// It just passes it down to Navigation</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">header</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span>></span>ShopSmart<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
{/* Header passes userName to Navigation */}
<span class="hljs-tag"><<span class="hljs-name">Navigation</span> <span class="hljs-attr">userName</span>=<span class="hljs-string">{userName}</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">header</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navigation</span>(<span class="hljs-params">{ userName }</span>) </span>{
<span class="hljs-comment">// Navigation also doesn't display userName</span>
<span class="hljs-comment">// It just passes it down to UserMenu</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">nav</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>></span>Home<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/products"</span>></span>Products<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
{/* Navigation passes userName to UserMenu */}
<span class="hljs-tag"><<span class="hljs-name">UserMenu</span> <span class="hljs-attr">userName</span>=<span class="hljs-string">{userName}</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">nav</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserMenu</span>(<span class="hljs-params">{ userName }</span>) </span>{
<span class="hljs-comment">// Finally! This component actually USES the userName</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"user-menu"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>Welcome, {userName}!<span class="hljs-tag"></<span class="hljs-name">span</span>></span> {/* userName is displayed here */}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
What’s the problem here?
-
Unnecessary complexity:
Header
andNavigation
don’t care aboutuserName
, but they have to know about it -
Tight coupling: If we want to change how
userName
works, we need to update multiple components -
Maintenance burden: Adding a new piece of user data means updating four different components
-
Confusing code: It’s hard to track where data is actually being used
This is a simple example with just one piece of data. Imagine this with 5-10 different pieces of data!
A realistic example: Shopping cart prop drilling
Now let’s see how this becomes a real nightmare with a shopping cart:
<span class="hljs-comment">// The main App component - this is where our cart data lives</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// useState is a React hook that creates state (data that can change)</span>
<span class="hljs-comment">// It returns an array with two items:</span>
<span class="hljs-comment">// 1. The current value (cartItems)</span>
<span class="hljs-comment">// 2. A function to update the value (setCartItems)</span>
<span class="hljs-keyword">const</span> [cartItems, setCartItems] = useState([]); <span class="hljs-comment">// Start with an empty array</span>
<span class="hljs-comment">// Another piece of state for the total price</span>
<span class="hljs-keyword">const</span> [cartTotal, setCartTotal] = useState(<span class="hljs-number">0</span>); <span class="hljs-comment">// Start with 0</span>
<span class="hljs-comment">// A function that adds items to the cart</span>
<span class="hljs-keyword">const</span> addToCart = <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
<span class="hljs-comment">// The spread operator (...) creates a new array with all existing items plus the new one</span>
<span class="hljs-keyword">const</span> newCartItems = [...cartItems, product];
setCartItems(newCartItems); <span class="hljs-comment">// Update the cart items</span>
setCartTotal(cartTotal + product.price); <span class="hljs-comment">// Update the total</span>
};
<span class="hljs-comment">// A function that removes items from the cart</span>
<span class="hljs-keyword">const</span> removeFromCart = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
<span class="hljs-comment">// filter() creates a new array with only items that don't match the ID</span>
<span class="hljs-keyword">const</span> updatedItems = cartItems.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId);
<span class="hljs-comment">// find() locates the item we're removing so we can subtract its price</span>
<span class="hljs-keyword">const</span> removedItem = cartItems.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
setCartItems(updatedItems); <span class="hljs-comment">// Update items</span>
setCartTotal(cartTotal - removedItem.price); <span class="hljs-comment">// Update total</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>></span>
{/*
We need to pass cart data to Header so it can show the cart count
Look how many props we need to pass!
*/}
<span class="hljs-tag"><<span class="hljs-name">Header</span>
<span class="hljs-attr">cartItems</span>=<span class="hljs-string">{cartItems}</span> // <span class="hljs-attr">Pass</span> <span class="hljs-attr">the</span> <span class="hljs-attr">entire</span> <span class="hljs-attr">cart</span> <span class="hljs-attr">array</span>
<span class="hljs-attr">cartTotal</span>=<span class="hljs-string">{cartTotal}</span> // <span class="hljs-attr">Pass</span> <span class="hljs-attr">the</span> <span class="hljs-attr">total</span> <span class="hljs-attr">price</span>
<span class="hljs-attr">addToCart</span>=<span class="hljs-string">{addToCart}</span> // <span class="hljs-attr">Pass</span> <span class="hljs-attr">the</span> <span class="hljs-attr">add</span> <span class="hljs-attr">function</span>
<span class="hljs-attr">removeFromCart</span>=<span class="hljs-string">{removeFromCart}</span> // <span class="hljs-attr">Pass</span> <span class="hljs-attr">the</span> <span class="hljs-attr">remove</span> <span class="hljs-attr">function</span>
/></span>
{/* MainContent also needs all the cart functionality */}
<span class="hljs-tag"><<span class="hljs-name">MainContent</span>
<span class="hljs-attr">cartItems</span>=<span class="hljs-string">{cartItems}</span>
<span class="hljs-attr">cartTotal</span>=<span class="hljs-string">{cartTotal}</span>
<span class="hljs-attr">addToCart</span>=<span class="hljs-string">{addToCart}</span>
<span class="hljs-attr">removeFromCart</span>=<span class="hljs-string">{removeFromCart}</span>
/></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Now let’s see what happens in the Header component:
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ cartItems, cartTotal, addToCart, removeFromCart }</span>) </span>{
<span class="hljs-comment">// Header receives all these props but only uses some of them</span>
<span class="hljs-comment">// It needs to pass them down to other components</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"header"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span>></span>ShopSmart<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
{/*
Navigation needs to show cart count, so we pass cartItems
But it doesn't need addToCart or removeFromCart
However, we might pass them "just in case"
*/}
<span class="hljs-tag"><<span class="hljs-name">Navigation</span>
<span class="hljs-attr">cartItems</span>=<span class="hljs-string">{cartItems}</span>
<span class="hljs-attr">cartTotal</span>=<span class="hljs-string">{cartTotal}</span>
<span class="hljs-attr">addToCart</span>=<span class="hljs-string">{addToCart}</span> // <span class="hljs-attr">Navigation</span> <span class="hljs-attr">doesn</span>'<span class="hljs-attr">t</span> <span class="hljs-attr">use</span> <span class="hljs-attr">this</span>
<span class="hljs-attr">removeFromCart</span>=<span class="hljs-string">{removeFromCart}</span> // <span class="hljs-attr">Navigation</span> <span class="hljs-attr">doesn</span>'<span class="hljs-attr">t</span> <span class="hljs-attr">use</span> <span class="hljs-attr">this</span> <span class="hljs-attr">either</span>
/></span>
{/* UserMenu might want to show cart total */}
<span class="hljs-tag"><<span class="hljs-name">UserMenu</span>
<span class="hljs-attr">cartTotal</span>=<span class="hljs-string">{cartTotal}</span>
<span class="hljs-attr">addToCart</span>=<span class="hljs-string">{addToCart}</span> // <span class="hljs-attr">UserMenu</span> <span class="hljs-attr">doesn</span>'<span class="hljs-attr">t</span> <span class="hljs-attr">use</span> <span class="hljs-attr">this</span>
<span class="hljs-attr">removeFromCart</span>=<span class="hljs-string">{removeFromCart}</span> // <span class="hljs-attr">UserMenu</span> <span class="hljs-attr">doesn</span>'<span class="hljs-attr">t</span> <span class="hljs-attr">use</span> <span class="hljs-attr">this</span> <span class="hljs-attr">either</span>
/></span>
<span class="hljs-tag"></<span class="hljs-name">header</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navigation</span>(<span class="hljs-params">{ cartItems, cartTotal, addToCart, removeFromCart }</span>) </span>{
<span class="hljs-comment">// Navigation only cares about showing the cart count</span>
<span class="hljs-comment">// But it receives ALL the cart props anyway</span>
<span class="hljs-keyword">const</span> itemCount = cartItems.length; <span class="hljs-comment">// Calculate how many items in cart</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">nav</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"navigation"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>></span>Home<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/products"</span>></span>Products<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
{/* This is the ONLY place Navigation actually uses the cart data */}
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/cart"</span>></span>
Cart
{/* Only show the badge if there are items */}
{itemCount > 0 && (
<span class="hljs-tag"><<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>{itemCount}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
)}
<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
<span class="hljs-tag"></<span class="hljs-name">nav</span>></span></span>
);
}
The problems are multiplying:
-
Props pollution: Components receive props they don’t use
-
Confusing interfaces: It’s hard to tell what each component actually needs
-
Change ripple effects: Modifying cart functionality might require changing 6+ components
-
Testing complexity: Testing Navigation requires mocking cart functions it doesn’t even use
-
Performance issues: Changing cart data causes ALL components in the chain to re-render
Why does this happen and get worse
This pattern emerges naturally because:
-
React is one-way data flow: Data can only flow down from parent to child
-
Component hierarchy: Your UI structure determines your data flow
-
No built-in sharing mechanism: React doesn’t provide a way for distant components to share data directly
As your app grows, you end up with:
-
10+ props being passed through 5+ levels
-
Components that exist just to pass props along
-
Developers afraid to refactor because they might break the prop chain
-
New features requiring changes to unrelated components
Solution 1: React Context API – Understanding the Concept
The Context API is React’s built-in solution for sharing data between components without prop drilling. Think of it like a radio station that broadcasts information, and any component can tune in to listen.
The radio station analogy
Traditional prop drilling is like passing a note through a chain of people:
-
Person A tells Person B
-
Person B tells Person C
-
Person C tells Person D
-
Only Person D actually needs the information
React Context is like a radio broadcast:
-
The radio station broadcasts information
-
Anyone with a radio can listen directly
-
No need to pass messages through intermediaries
What is createContext()
?
createContext()
is a React function that creates a “broadcasting system” for your data. It returns two things:
-
Provider: The “radio station” that broadcasts data
-
Consumer: The “radio” that components use to listen for data
<span class="hljs-keyword">import</span> { createContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-comment">// createContext() creates our "radio station"</span>
<span class="hljs-comment">// We can pass a default value (like a default radio frequency)</span>
<span class="hljs-keyword">const</span> CartContext = createContext();
<span class="hljs-comment">// CartContext now contains:</span>
<span class="hljs-comment">// - CartContext.Provider (the broadcaster)</span>
<span class="hljs-comment">// - CartContext.Consumer (the listener, though we rarely use this directly)</span>
What createContext() actually does:
-
Creates a special React object that can share data
-
The default value is used when a component tries to access the context but isn’t inside a Provider
-
Returns an object with Provider and Consumer components
Creating a basic Context Provider
A Provider is a component that makes data available to all its children:
<span class="hljs-keyword">import</span> { createContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-comment">// Step 1: Create the context</span>
<span class="hljs-keyword">const</span> CartContext = createContext();
<span class="hljs-comment">// Step 2: Create a Provider component</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-comment">// children is a special prop that contains whatever components are inside CartProvider</span>
<span class="hljs-comment">// This is our cart state - same as before</span>
<span class="hljs-keyword">const</span> [cartItems, setCartItems] = useState([]);
<span class="hljs-keyword">const</span> [cartTotal, setCartTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Our cart functions</span>
<span class="hljs-keyword">const</span> addToCart = <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
<span class="hljs-keyword">const</span> newCartItems = [...cartItems, product];
setCartItems(newCartItems);
setCartTotal(cartTotal + product.price);
};
<span class="hljs-keyword">const</span> removeFromCart = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
<span class="hljs-keyword">const</span> updatedItems = cartItems.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId);
<span class="hljs-keyword">const</span> removedItem = cartItems.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
setCartItems(updatedItems);
<span class="hljs-keyword">if</span> (removedItem) { <span class="hljs-comment">// Make sure we found the item before subtracting</span>
setCartTotal(cartTotal - removedItem.price);
}
};
<span class="hljs-comment">// This object contains everything we want to share</span>
<span class="hljs-keyword">const</span> cartValue = {
cartItems, <span class="hljs-comment">// The array of items</span>
cartTotal, <span class="hljs-comment">// The total price</span>
addToCart, <span class="hljs-comment">// Function to add items</span>
removeFromCart, <span class="hljs-comment">// Function to remove items</span>
<span class="hljs-attr">itemCount</span>: cartItems.length <span class="hljs-comment">// Calculated value for convenience</span>
};
<span class="hljs-keyword">return</span> (
<span class="hljs-comment">/*
CartContext.Provider is the "radio station"
- value prop is what gets "broadcasted"
- children are all the components that can "listen" to this broadcast
*/</span>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{cartValue}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
Let’s break down this Provider:
-
Function component:
CartProvider
is just a regular React component -
children prop: This contains whatever JSX is placed inside
<CartProvider>...</CartProvider>
-
State management: We manage cart state exactly like before with
useState
-
value prop: This is crucial – whatever we put here becomes available to all child components
-
Return JSX: We wrap
children
inCartContext.Provider
to “broadcast” our data
Understanding the useContext hook
useContext is a React hook that lets components “tune in” to a Context broadcast:
<span class="hljs-keyword">import</span> { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// useContext(CartContext) "tunes in" to our cart data</span>
<span class="hljs-comment">// It returns whatever we put in the value prop of CartProvider</span>
<span class="hljs-keyword">const</span> cartData = useContext(CartContext);
<span class="hljs-comment">// cartData now contains: { cartItems, cartTotal, addToCart, removeFromCart, itemCount }</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>
{/* We can access any property from our cartValue object */}
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>Cart ({cartData.itemCount})<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
What useContext() does:
-
Looks up the component tree: Finds the nearest CartContext.Provider
-
Returns the value: Gives us whatever was passed to the value prop
-
Automatically re-renders: When the context value changes, this component updates
-
Throws an error: If no Provider is found, it returns the default value (or undefined)
Creating a custom hook for cleaner usage
Instead of using useContext(CartContext)
everywhere, we can create a custom hook:
<span class="hljs-comment">// Custom hook that wraps useContext</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCart</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Get the cart data from context</span>
<span class="hljs-keyword">const</span> context = useContext(CartContext);
<span class="hljs-comment">// Check if we're inside a CartProvider</span>
<span class="hljs-keyword">if</span> (context === <span class="hljs-literal">undefined</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'useCart must be used within a CartProvider'</span>);
}
<span class="hljs-keyword">return</span> context;
}
<span class="hljs-comment">// Now components can use our custom hook</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { itemCount } = useCart(); <span class="hljs-comment">// Much cleaner!</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>Cart ({itemCount})<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
There are various reasons to create a custom hook:
-
Better error messages: We get a clear error if someone forgets the Provider
-
Cleaner imports: Import
useCart
instead ofuseContext
andCartContext
-
Future flexibility: We can add logic to the hook later if needed
-
Type safety: In TypeScript, this provides better type inference
Putting it all together: Complete Context example
Now let’s see how our shopping cart looks with Context instead of prop drilling:
<span class="hljs-keyword">import</span> { createContext, useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-comment">// Step 1: Create the context</span>
<span class="hljs-keyword">const</span> CartContext = createContext();
<span class="hljs-comment">// Step 2: Create custom hook</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCart</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> context = useContext(CartContext);
<span class="hljs-keyword">if</span> (context === <span class="hljs-literal">undefined</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'useCart must be used within a CartProvider'</span>);
}
<span class="hljs-keyword">return</span> context;
}
<span class="hljs-comment">// Step 3: Create the Provider</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [cartItems, setCartItems] = useState([]);
<span class="hljs-keyword">const</span> [cartTotal, setCartTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> addToCart = <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
<span class="hljs-keyword">const</span> newCartItems = [...cartItems, product];
setCartItems(newCartItems);
setCartTotal(cartTotal + product.price);
};
<span class="hljs-keyword">const</span> removeFromCart = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
<span class="hljs-keyword">const</span> updatedItems = cartItems.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId);
<span class="hljs-keyword">const</span> removedItem = cartItems.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
setCartItems(updatedItems);
<span class="hljs-keyword">if</span> (removedItem) {
setCartTotal(cartTotal - removedItem.price);
}
};
<span class="hljs-keyword">const</span> value = {
cartItems,
cartTotal,
addToCart,
removeFromCart,
<span class="hljs-attr">itemCount</span>: cartItems.length
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Step 4: Use the context in components</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="hljs-comment">// Wrap our app in the CartProvider</span>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>></span>
{/* No props needed! */}
<span class="hljs-tag"><<span class="hljs-name">Header</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">MainContent</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">CartProvider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Header doesn't need any cart props</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"header"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span>></span>ShopSmart<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Navigation</span> /></span> {/* No props passed here either */}
<span class="hljs-tag"><<span class="hljs-name">UserMenu</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">header</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navigation</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Navigation gets cart data directly from context</span>
<span class="hljs-keyword">const</span> { itemCount } = useCart();
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">nav</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"navigation"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>></span>Home<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/products"</span>></span>Products<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
<span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/cart"</span>></span>
Cart
{itemCount > 0 && (
<span class="hljs-tag"><<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>{itemCount}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
)}
<span class="hljs-tag"></<span class="hljs-name">a</span>></span>
<span class="hljs-tag"></<span class="hljs-name">nav</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductCard</span>(<span class="hljs-params">{ product }</span>) </span>{
<span class="hljs-comment">// ProductCard gets the addToCart function directly</span>
<span class="hljs-keyword">const</span> { addToCart } = useCart();
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product-card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>{product.name}<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>{product.description}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"price"</span>></span>${product.price}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
{/* No prop drilling needed! */}
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> addToCart(product)}>
Add to Cart
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartSidebar</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// CartSidebar gets cart items and remove function directly</span>
<span class="hljs-keyword">const</span> { cartItems, removeFromCart } = useCart();
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-sidebar"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>Your Cart<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
{cartItems.length === 0 ? (
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Your cart is empty<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
) : (
<span class="hljs-tag"><<span class="hljs-name">ul</span>></span>
{cartItems.map(item => (
<span class="hljs-tag"><<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>{item.name} - ${item.price}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> removeFromCart(item.id)}>
Remove
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">li</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">ul</span>></span>
)}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// Export our Provider and hook for use in other files</span>
<span class="hljs-keyword">export</span> { CartProvider, useCart };
Compare this to our prop drilling version:
Before (Prop Drilling):
-
App passes 4 props to Header
-
Header passes 4 props to Navigation (even though Navigation only needs 1)
-
Navigation receives props it doesn’t use
-
Every component in the chain needs to know about cart structure
After (Context):
-
App only needs to wrap components in CartProvider
-
Header doesn’t handle any cart props
-
Navigation directly gets only what it needs (
itemCount
) -
ProductCard directly gets only what it needs (
addToCart
) -
Each component is independent and focused
Advanced Context Patterns and Concepts
Now that you understand the basics, let’s explore more sophisticated Context patterns that you’ll encounter in real applications.
Multiple contexts for separation of concerns
In real applications, you don’t want to put everything in one giant context. Instead, you can create separate contexts for different domains:
<span class="hljs-comment">// Separate contexts for different types of data</span>
<span class="hljs-keyword">const</span> UserContext = createContext(); <span class="hljs-comment">// User authentication and profile</span>
<span class="hljs-keyword">const</span> ThemeContext = createContext(); <span class="hljs-comment">// UI theme and appearance </span>
<span class="hljs-keyword">const</span> CartContext = createContext(); <span class="hljs-comment">// Shopping cart functionality</span>
<span class="hljs-comment">// User Provider - handles authentication</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Current user data</span>
<span class="hljs-keyword">const</span> [isLoggedIn, setIsLoggedIn] = useState(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Login status</span>
<span class="hljs-comment">// Function to log in a user</span>
<span class="hljs-keyword">const</span> login = <span class="hljs-keyword">async</span> (email, password) => {
<span class="hljs-keyword">try</span> {
<span class="hljs-comment">// authAPI would be your authentication service (like Firebase, Auth0, etc.)</span>
<span class="hljs-keyword">const</span> userData = <span class="hljs-keyword">await</span> authAPI.login(email, password);
setUser(userData); <span class="hljs-comment">// Store user information</span>
setIsLoggedIn(<span class="hljs-literal">true</span>); <span class="hljs-comment">// Mark as logged in</span>
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Login failed:'</span>, error);
<span class="hljs-comment">// Handle login errors (show message to user, etc.)</span>
}
};
<span class="hljs-comment">// Function to log out a user</span>
<span class="hljs-keyword">const</span> logout = <span class="hljs-function">() =></span> {
setUser(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Clear user data</span>
setIsLoggedIn(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Mark as logged out</span>
<span class="hljs-comment">// You might also clear localStorage, redirect to login page, etc.</span>
};
<span class="hljs-keyword">const</span> value = {
user, <span class="hljs-comment">// Current user object: { id, name, email, etc. }</span>
isLoggedIn, <span class="hljs-comment">// Boolean: true if user is logged in</span>
login, <span class="hljs-comment">// Function to log in</span>
logout, <span class="hljs-comment">// Function to log out</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">UserContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Theme Provider - handles UI appearance</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>); <span class="hljs-comment">// 'light' or 'dark'</span>
<span class="hljs-keyword">const</span> [fontSize, setFontSize] = useState(<span class="hljs-string">'medium'</span>); <span class="hljs-comment">// 'small', 'medium', 'large'</span>
<span class="hljs-comment">// Function to switch between light and dark themes</span>
<span class="hljs-keyword">const</span> toggleTheme = <span class="hljs-function">() =></span> {
setTheme(<span class="hljs-function"><span class="hljs-params">currentTheme</span> =></span> currentTheme === <span class="hljs-string">'light'</span> ? <span class="hljs-string">'dark'</span> : <span class="hljs-string">'light'</span>);
};
<span class="hljs-comment">// Function to update font size</span>
<span class="hljs-keyword">const</span> updateFontSize = <span class="hljs-function">(<span class="hljs-params">size</span>) =></span> {
<span class="hljs-keyword">if</span> ([<span class="hljs-string">'small'</span>, <span class="hljs-string">'medium'</span>, <span class="hljs-string">'large'</span>].includes(size)) {
setFontSize(size);
}
};
<span class="hljs-keyword">const</span> value = {
theme, <span class="hljs-comment">// Current theme: 'light' or 'dark'</span>
fontSize, <span class="hljs-comment">// Current font size: 'small', 'medium', or 'large'</span>
toggleTheme, <span class="hljs-comment">// Function to switch themes</span>
updateFontSize, <span class="hljs-comment">// Function to change font size</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">ThemeContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Custom hooks for each context</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useUser</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> context = useContext(UserContext);
<span class="hljs-keyword">if</span> (context === <span class="hljs-literal">undefined</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'useUser must be used within a UserProvider'</span>);
}
<span class="hljs-keyword">return</span> context;
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useTheme</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> context = useContext(ThemeContext);
<span class="hljs-keyword">if</span> (context === <span class="hljs-literal">undefined</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'useTheme must be used within a ThemeProvider'</span>);
}
<span class="hljs-keyword">return</span> context;
}
<span class="hljs-comment">// App with multiple providers</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="hljs-comment">// You can nest providers in any order</span>
<span class="hljs-comment">// Each provider makes its data available to all children</span>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">ThemeProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">CartProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Header</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">MainContent</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">Footer</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">CartProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">ThemeProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">UserProvider</span>></span></span>
);
}
<span class="hljs-comment">// Component using multiple contexts</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { user, logout } = useUser(); <span class="hljs-comment">// Get user data</span>
<span class="hljs-keyword">const</span> { theme, toggleTheme } = useTheme(); <span class="hljs-comment">// Get theme data</span>
<span class="hljs-keyword">const</span> { itemCount } = useCart(); <span class="hljs-comment">// Get cart data</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">user-profile</span> <span class="hljs-attr">theme-</span>${<span class="hljs-attr">theme</span>}`}></span>
<span class="hljs-tag"><<span class="hljs-name">h2</span>></span>Welcome, {user?.name}!<span class="hljs-tag"></<span class="hljs-name">h2</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Items in cart: {itemCount}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleTheme}</span>></span>
Switch to {theme === 'light' ? 'dark' : 'light'} theme
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{logout}</span>></span>
Logout
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
So why should you use separate contexts? First, performance considerations: components only re-render when the specific context they use changes. Second, it’s helpful for organizational purposes as related functionality is grouped together. It’s also great for reusability, as you can use UserProvider in different apps without cart functionality. And finally, it’s easier to test components that only depend on specific contexts.
Understanding useReducer
for complex state logic
When your context state becomes complex with multiple related values and complex update logic, useReducer
is often a better choice than multiple useState
calls.
What is useReducer? useReducer
is a React hook that manages state through a “reducer” function. Instead of directly setting state, you “dispatch actions” that describe what happened, and the reducer decides how to update the state.
Think of it like a vending machine:
-
You press buttons (dispatch actions) to describe what you want
-
The machine has internal logic (reducer) that determines what happens
-
The machine gives you the result (new state)
<span class="hljs-comment">// First, let's define what actions our cart can handle</span>
<span class="hljs-keyword">const</span> cartActions = {
<span class="hljs-attr">ADD_ITEM</span>: <span class="hljs-string">'ADD_ITEM'</span>, <span class="hljs-comment">// Add a product to cart</span>
<span class="hljs-attr">REMOVE_ITEM</span>: <span class="hljs-string">'REMOVE_ITEM'</span>, <span class="hljs-comment">// Remove a product completely</span>
<span class="hljs-attr">UPDATE_QUANTITY</span>: <span class="hljs-string">'UPDATE_QUANTITY'</span>, <span class="hljs-comment">// Change quantity of existing item</span>
<span class="hljs-attr">CLEAR_CART</span>: <span class="hljs-string">'CLEAR_CART'</span>, <span class="hljs-comment">// Empty the entire cart</span>
<span class="hljs-attr">APPLY_DISCOUNT</span>: <span class="hljs-string">'APPLY_DISCOUNT'</span> <span class="hljs-comment">// Apply a discount code</span>
};
<span class="hljs-comment">// The reducer function: decides how state changes based on actions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cartReducer</span>(<span class="hljs-params">state, action</span>) </span>{
<span class="hljs-comment">// state: current cart state</span>
<span class="hljs-comment">// action: object describing what happened, like { type: 'ADD_ITEM', payload: product }</span>
<span class="hljs-keyword">switch</span> (action.type) {
<span class="hljs-keyword">case</span> cartActions.ADD_ITEM: {
<span class="hljs-keyword">const</span> product = action.payload; <span class="hljs-comment">// The product being added</span>
<span class="hljs-comment">// Check if this product is already in the cart</span>
<span class="hljs-keyword">const</span> existingItemIndex = state.items.findIndex(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === product.id);
<span class="hljs-keyword">if</span> (existingItemIndex >= <span class="hljs-number">0</span>) {
<span class="hljs-comment">// Product exists: increase its quantity</span>
<span class="hljs-keyword">const</span> updatedItems = [...state.items]; <span class="hljs-comment">// Create a copy of items array</span>
updatedItems[existingItemIndex] = {
...updatedItems[existingItemIndex], <span class="hljs-comment">// Copy existing item properties</span>
<span class="hljs-attr">quantity</span>: updatedItems[existingItemIndex].quantity + <span class="hljs-number">1</span> <span class="hljs-comment">// Increase quantity</span>
};
<span class="hljs-keyword">return</span> {
...state, <span class="hljs-comment">// Keep other state properties</span>
<span class="hljs-attr">items</span>: updatedItems, <span class="hljs-comment">// Update items array</span>
<span class="hljs-attr">total</span>: state.total + product.price, <span class="hljs-comment">// Add to total</span>
<span class="hljs-attr">itemCount</span>: state.itemCount + <span class="hljs-number">1</span>, <span class="hljs-comment">// Increase count</span>
};
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// New product: add it to cart</span>
<span class="hljs-keyword">const</span> newItem = {
...product, <span class="hljs-comment">// Copy all product properties (id, name, price, and so on)</span>
<span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> <span class="hljs-comment">// Add quantity property</span>
};
<span class="hljs-keyword">return</span> {
...state, <span class="hljs-comment">// Keep other state properties</span>
<span class="hljs-attr">items</span>: [...state.items, newItem], <span class="hljs-comment">// Add new item to array</span>
<span class="hljs-attr">total</span>: state.total + product.price, <span class="hljs-comment">// Add to total</span>
<span class="hljs-attr">itemCount</span>: state.itemCount + <span class="hljs-number">1</span>, <span class="hljs-comment">// Increase count</span>
};
}
}
<span class="hljs-keyword">case</span> cartActions.REMOVE_ITEM: {
<span class="hljs-keyword">const</span> productId = action.payload; <span class="hljs-comment">// ID of product to remove</span>
<span class="hljs-comment">// Find the item being removed</span>
<span class="hljs-keyword">const</span> itemToRemove = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-comment">// If item doesn't exist, return state unchanged</span>
<span class="hljs-keyword">if</span> (!itemToRemove) <span class="hljs-keyword">return</span> state;
<span class="hljs-comment">// Remove the item from the array</span>
<span class="hljs-keyword">const</span> updatedItems = state.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId);
<span class="hljs-keyword">return</span> {
...state,
<span class="hljs-attr">items</span>: updatedItems,
<span class="hljs-comment">// Subtract the total price of removed item (price × quantity)</span>
<span class="hljs-attr">total</span>: state.total - (itemToRemove.price * itemToRemove.quantity),
<span class="hljs-comment">// Subtract the quantity of removed item</span>
<span class="hljs-attr">itemCount</span>: state.itemCount - itemToRemove.quantity,
};
}
<span class="hljs-keyword">case</span> cartActions.UPDATE_QUANTITY: {
<span class="hljs-keyword">const</span> { productId, quantity } = action.payload;
<span class="hljs-comment">// If quantity is 0 or less, remove the item</span>
<span class="hljs-keyword">if</span> (quantity <= <span class="hljs-number">0</span>) {
<span class="hljs-keyword">return</span> cartReducer(state, {
<span class="hljs-attr">type</span>: cartActions.REMOVE_ITEM,
<span class="hljs-attr">payload</span>: productId
});
}
<span class="hljs-keyword">const</span> updatedItems = state.items.map(<span class="hljs-function"><span class="hljs-params">item</span> =></span> {
<span class="hljs-keyword">if</span> (item.id === productId) {
<span class="hljs-keyword">return</span> { ...item, quantity }; <span class="hljs-comment">// Update this item's quantity</span>
}
<span class="hljs-keyword">return</span> item; <span class="hljs-comment">// Keep other items unchanged</span>
});
<span class="hljs-comment">// Find the item to calculate price difference</span>
<span class="hljs-keyword">const</span> item = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (!item) <span class="hljs-keyword">return</span> state; <span class="hljs-comment">// Item not found, no change</span>
<span class="hljs-keyword">const</span> quantityDifference = quantity - item.quantity;
<span class="hljs-keyword">return</span> {
...state,
<span class="hljs-attr">items</span>: updatedItems,
<span class="hljs-attr">total</span>: state.total + (item.price * quantityDifference),
<span class="hljs-attr">itemCount</span>: state.itemCount + quantityDifference,
};
}
<span class="hljs-keyword">case</span> cartActions.CLEAR_CART: {
<span class="hljs-comment">// Reset everything to initial state</span>
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">discount</span>: <span class="hljs-number">0</span>,
};
}
<span class="hljs-keyword">case</span> cartActions.APPLY_DISCOUNT: {
<span class="hljs-keyword">const</span> discountPercent = action.payload; <span class="hljs-comment">// Discount percentage (for example, 10 for 10%)</span>
<span class="hljs-keyword">const</span> discountAmount = state.total * (discountPercent / <span class="hljs-number">100</span>);
<span class="hljs-keyword">return</span> {
...state,
<span class="hljs-attr">discount</span>: discountAmount,
};
}
<span class="hljs-attr">default</span>:
<span class="hljs-comment">// If we don't recognize the action type, return state unchanged</span>
<span class="hljs-keyword">return</span> state;
}
}
<span class="hljs-comment">// Updated CartProvider using useReducer</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-comment">// Initial state for our cart</span>
<span class="hljs-keyword">const</span> initialState = {
<span class="hljs-attr">items</span>: [], <span class="hljs-comment">// Array of cart items</span>
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>, <span class="hljs-comment">// Total price before discount</span>
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>, <span class="hljs-comment">// Total number of items</span>
<span class="hljs-attr">discount</span>: <span class="hljs-number">0</span>, <span class="hljs-comment">// Discount amount</span>
};
<span class="hljs-comment">// useReducer takes two arguments:</span>
<span class="hljs-comment">// 1. The reducer function (cartReducer)</span>
<span class="hljs-comment">// 2. The initial state</span>
<span class="hljs-comment">// It returns:</span>
<span class="hljs-comment">// 1. Current state</span>
<span class="hljs-comment">// 2. Dispatch function to send actions</span>
<span class="hljs-keyword">const</span> [state, dispatch] = useReducer(cartReducer, initialState);
<span class="hljs-comment">// Action creator functions - these create action objects</span>
<span class="hljs-keyword">const</span> addItem = <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
dispatch({
<span class="hljs-attr">type</span>: cartActions.ADD_ITEM, <span class="hljs-comment">// What happened</span>
<span class="hljs-attr">payload</span>: product <span class="hljs-comment">// The data needed</span>
});
};
<span class="hljs-keyword">const</span> removeItem = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
dispatch({
<span class="hljs-attr">type</span>: cartActions.REMOVE_ITEM,
<span class="hljs-attr">payload</span>: productId
});
};
<span class="hljs-keyword">const</span> updateQuantity = <span class="hljs-function">(<span class="hljs-params">productId, quantity</span>) =></span> {
dispatch({
<span class="hljs-attr">type</span>: cartActions.UPDATE_QUANTITY,
<span class="hljs-attr">payload</span>: { productId, quantity }
});
};
<span class="hljs-keyword">const</span> clearCart = <span class="hljs-function">() =></span> {
dispatch({ <span class="hljs-attr">type</span>: cartActions.CLEAR_CART });
};
<span class="hljs-keyword">const</span> applyDiscount = <span class="hljs-function">(<span class="hljs-params">discountPercent</span>) =></span> {
dispatch({
<span class="hljs-attr">type</span>: cartActions.APPLY_DISCOUNT,
<span class="hljs-attr">payload</span>: discountPercent
});
};
<span class="hljs-comment">// Calculate final total (total minus discount)</span>
<span class="hljs-keyword">const</span> finalTotal = state.total - state.discount;
<span class="hljs-keyword">const</span> value = {
<span class="hljs-comment">// State values</span>
<span class="hljs-attr">items</span>: state.items,
<span class="hljs-attr">total</span>: state.total,
<span class="hljs-attr">itemCount</span>: state.itemCount,
<span class="hljs-attr">discount</span>: state.discount,
finalTotal,
<span class="hljs-comment">// Action functions</span>
addItem,
removeItem,
updateQuantity,
clearCart,
applyDiscount,
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
useReducer
has various benefits over multiple useState
s:
-
Centralized logic: All cart update logic is in one place (the reducer)
-
Predictable updates: Actions describe what happened, reducer decides how to update
-
Easier testing: You can test the reducer function independently
-
Better for complex state: When state has multiple related values that change together
-
Debugging: You can log all actions to see exactly what happened
Solution 2: State Management Libraries Explained
While React Context is great for medium-complexity applications, larger applications often benefit from dedicated state management libraries. Let’s explore the most popular options.
Understanding Redux: The predictable state container
Redux is a library that provides a single, centralized store for all your application state. Think of it like a giant database that your entire app shares, with strict rules about how data can be changed.
Core Redux concepts
1. Store: The single source of truth for your app’s state
<span class="hljs-comment">// The store is like a database that holds ALL your app's state</span>
<span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-comment">// Example of what your entire app state might look like</span>
<span class="hljs-keyword">const</span> initialAppState = {
<span class="hljs-attr">user</span>: {
<span class="hljs-attr">id</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">email</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">isLoggedIn</span>: <span class="hljs-literal">false</span>
},
<span class="hljs-attr">cart</span>: {
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">discount</span>: <span class="hljs-number">0</span>
},
<span class="hljs-attr">ui</span>: {
<span class="hljs-attr">theme</span>: <span class="hljs-string">'light'</span>,
<span class="hljs-attr">sidebarOpen</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>
}
};
<span class="hljs-comment">// The store holds this state and provides methods to interact with it</span>
<span class="hljs-keyword">const</span> store = createStore(rootReducer, initialAppState);
<span class="hljs-comment">// You can get the current state at any time</span>
<span class="hljs-keyword">const</span> currentState = store.getState();
<span class="hljs-built_in">console</span>.log(currentState.cart.items); <span class="hljs-comment">// Access cart items</span>
<span class="hljs-built_in">console</span>.log(currentState.user.name); <span class="hljs-comment">// Access user name</span>
2. Actions: Plain objects that describe what happened
<span class="hljs-comment">// Actions are like event descriptions - they tell Redux what happened</span>
<span class="hljs-comment">// They must have a 'type' property and optionally a 'payload'</span>
<span class="hljs-comment">// Action to add item to cart</span>
<span class="hljs-keyword">const</span> addItemAction = {
<span class="hljs-attr">type</span>: <span class="hljs-string">'cart/addItem'</span>, <span class="hljs-comment">// Describes what happened</span>
<span class="hljs-attr">payload</span>: { <span class="hljs-comment">// The data needed</span>
<span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'T-Shirt'</span>,
<span class="hljs-attr">price</span>: <span class="hljs-number">25</span>
}
};
<span class="hljs-comment">// Action to log in user</span>
<span class="hljs-keyword">const</span> loginAction = {
<span class="hljs-attr">type</span>: <span class="hljs-string">'user/login'</span>,
<span class="hljs-attr">payload</span>: {
<span class="hljs-attr">id</span>: <span class="hljs-number">123</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>,
<span class="hljs-attr">email</span>: <span class="hljs-string">'alice@example.com'</span>
}
};
<span class="hljs-comment">// Action to toggle theme</span>
<span class="hljs-keyword">const</span> toggleThemeAction = {
<span class="hljs-attr">type</span>: <span class="hljs-string">'ui/toggleTheme'</span> <span class="hljs-comment">// No payload needed</span>
};
<span class="hljs-comment">// Action creators: functions that create actions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addItem</span>(<span class="hljs-params">product</span>) </span>{
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">type</span>: <span class="hljs-string">'cart/addItem'</span>,
<span class="hljs-attr">payload</span>: product
};
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loginUser</span>(<span class="hljs-params">userData</span>) </span>{
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">type</span>: <span class="hljs-string">'user/login'</span>,
<span class="hljs-attr">payload</span>: userData
};
}
<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> action = addItem({ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'T-Shirt'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">25</span> });
<span class="hljs-built_in">console</span>.log(action); <span class="hljs-comment">// { type: 'cart/addItem', payload: { ... } }</span>
3. Reducers: Pure functions that specify how state changes
<span class="hljs-comment">// A reducer is a function that takes current state and an action,</span>
<span class="hljs-comment">// and returns new state. It must NEVER modify the existing state.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cartReducer</span>(<span class="hljs-params">state = { items: [], total: <span class="hljs-number">0</span> }, action</span>) </span>{
<span class="hljs-comment">// state: current cart state</span>
<span class="hljs-comment">// action: the action object describing what happened</span>
<span class="hljs-keyword">switch</span> (action.type) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'cart/addItem'</span>: {
<span class="hljs-keyword">const</span> product = action.payload;
<span class="hljs-comment">// NEVER modify existing state directly!</span>
<span class="hljs-comment">// Instead, create new objects/arrays</span>
<span class="hljs-keyword">return</span> {
...state, <span class="hljs-comment">// Copy existing state</span>
<span class="hljs-attr">items</span>: [...state.items, product], <span class="hljs-comment">// Create new items array</span>
<span class="hljs-attr">total</span>: state.total + product.price <span class="hljs-comment">// Calculate new total</span>
};
}
<span class="hljs-keyword">case</span> <span class="hljs-string">'cart/removeItem'</span>: {
<span class="hljs-keyword">const</span> productId = action.payload;
<span class="hljs-keyword">const</span> itemToRemove = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">return</span> {
...state,
<span class="hljs-attr">items</span>: state.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId), <span class="hljs-comment">// New array without item</span>
<span class="hljs-attr">total</span>: state.total - (itemToRemove?.price || <span class="hljs-number">0</span>) <span class="hljs-comment">// Subtract price</span>
};
}
<span class="hljs-attr">default</span>:
<span class="hljs-comment">// Always return current state for unknown actions</span>
<span class="hljs-keyword">return</span> state;
}
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">userReducer</span>(<span class="hljs-params">state = { id: null, name: <span class="hljs-string">''</span>, isLoggedIn: false }, action</span>) </span>{
<span class="hljs-keyword">switch</span> (action.type) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'user/login'</span>:
<span class="hljs-keyword">return</span> {
...state,
...action.payload, <span class="hljs-comment">// Merge user data from payload</span>
<span class="hljs-attr">isLoggedIn</span>: <span class="hljs-literal">true</span> <span class="hljs-comment">// Set login status</span>
};
<span class="hljs-keyword">case</span> <span class="hljs-string">'user/logout'</span>:
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">id</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">email</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">isLoggedIn</span>: <span class="hljs-literal">false</span>
};
<span class="hljs-keyword">default</span>:
<span class="hljs-keyword">return</span> state;
}
}
<span class="hljs-comment">// Root reducer: combines all reducers</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rootReducer</span>(<span class="hljs-params">state = {}, action</span>) </span>{
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">cart</span>: cartReducer(state.cart, action), <span class="hljs-comment">// Handle cart actions</span>
<span class="hljs-attr">user</span>: userReducer(state.user, action), <span class="hljs-comment">// Handle user actions</span>
};
}
4. Dispatch: The only way to trigger state changes
<span class="hljs-comment">// You can't change Redux state directly</span>
<span class="hljs-comment">// Instead, you dispatch actions to describe what should happen</span>
<span class="hljs-comment">// Get the store's dispatch function</span>
<span class="hljs-keyword">const</span> { dispatch } = store;
<span class="hljs-comment">// Dispatch actions to change state</span>
dispatch(addItem({ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'T-Shirt'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">25</span> }));
dispatch(loginUser({ <span class="hljs-attr">id</span>: <span class="hljs-number">123</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">email</span>: <span class="hljs-string">'alice@example.com'</span> }));
dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'user/logout'</span> });
<span class="hljs-comment">// Each dispatch triggers the reducer, which returns new state</span>
How to use Redux in React components
To use Redux in React, you need the react-redux
library, which provides two main tools:
1. Provider: Makes the store available to all components
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-comment">// Create your Redux store</span>
<span class="hljs-keyword">const</span> store = createStore(rootReducer);
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="hljs-comment">// Provider makes the store available to all child components</span>
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Header</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">ProductList</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">Cart</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">Provider</span>></span></span>
);
}
2. useSelector and useDispatch hooks
<span class="hljs-keyword">import</span> { useSelector, useDispatch } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductCard</span>(<span class="hljs-params">{ product }</span>) </span>{
<span class="hljs-comment">// useSelector extracts data from the Redux store</span>
<span class="hljs-comment">// The function you pass gets the entire state object</span>
<span class="hljs-keyword">const</span> cartItems = useSelector(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.cart.items);
<span class="hljs-comment">// useDispatch returns the dispatch function</span>
<span class="hljs-keyword">const</span> dispatch = useDispatch();
<span class="hljs-comment">// Check if this product is already in cart</span>
<span class="hljs-keyword">const</span> isInCart = cartItems.some(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === product.id);
<span class="hljs-keyword">const</span> handleAddToCart = <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Dispatch an action to add item</span>
dispatch(addItem(product));
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product-card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>{product.name}<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>{product.description}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"price"</span>></span>${product.price}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span>
<span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleAddToCart}</span>
<span class="hljs-attr">disabled</span>=<span class="hljs-string">{isInCart}</span>
></span>
{isInCart ? 'In Cart' : 'Add to Cart'}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartSummary</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Select multiple pieces of state</span>
<span class="hljs-keyword">const</span> { items, total } = useSelector(<span class="hljs-function"><span class="hljs-params">state</span> =></span> ({
<span class="hljs-attr">items</span>: state.cart.items,
<span class="hljs-attr">total</span>: state.cart.total
}));
<span class="hljs-keyword">const</span> dispatch = useDispatch();
<span class="hljs-keyword">const</span> handleRemoveItem = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
dispatch(removeItem(productId));
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-summary"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>Cart Summary<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Total: ${total.toFixed(2)}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
{items.map(item => (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-item"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>{item.name} - ${item.price}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> handleRemoveItem(item.id)}>
Remove
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Redux Toolkit: Modern Redux made simple
Redux Toolkit is the official, recommended way to write Redux logic. It simplifies Redux by providing utilities that reduce boilerplate code.
What Redux Toolkit provides
-
createSlice: Generates action creators and reducers automatically
-
configureStore: Sets up the store with good defaults
-
Immer integration: Lets you write “mutative” logic that’s actually immutable
<span class="hljs-keyword">import</span> { createSlice, configureStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'@reduxjs/toolkit'</span>;
<span class="hljs-comment">// createSlice generates action creators and reducers automatically</span>
<span class="hljs-keyword">const</span> cartSlice = createSlice({
<span class="hljs-attr">name</span>: <span class="hljs-string">'cart'</span>, <span class="hljs-comment">// Name for this slice of state</span>
<span class="hljs-attr">initialState</span>: { <span class="hljs-comment">// Initial state value</span>
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>
},
<span class="hljs-attr">reducers</span>: { <span class="hljs-comment">// Reducer functions</span>
<span class="hljs-comment">// Redux Toolkit uses Immer internally, so we can "mutate" state</span>
<span class="hljs-comment">// (It's actually creating immutable updates behind the scenes)</span>
<span class="hljs-attr">addItem</span>: <span class="hljs-function">(<span class="hljs-params">state, action</span>) =></span> {
<span class="hljs-keyword">const</span> product = action.payload;
<span class="hljs-keyword">const</span> existingItem = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === product.id);
<span class="hljs-keyword">if</span> (existingItem) {
existingItem.quantity += <span class="hljs-number">1</span>; <span class="hljs-comment">// This looks like mutation!</span>
} <span class="hljs-keyword">else</span> {
state.items.push({ <span class="hljs-comment">// This looks like mutation!</span>
...product,
<span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span>
});
}
state.total += product.price; <span class="hljs-comment">// This looks like mutation!</span>
},
<span class="hljs-attr">removeItem</span>: <span class="hljs-function">(<span class="hljs-params">state, action</span>) =></span> {
<span class="hljs-keyword">const</span> productId = action.payload;
<span class="hljs-keyword">const</span> itemIndex = state.items.findIndex(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (itemIndex >= <span class="hljs-number">0</span>) {
<span class="hljs-keyword">const</span> item = state.items[itemIndex];
state.total -= item.price * item.quantity;
state.items.splice(itemIndex, <span class="hljs-number">1</span>); <span class="hljs-comment">// Remove from array</span>
}
},
<span class="hljs-attr">updateQuantity</span>: <span class="hljs-function">(<span class="hljs-params">state, action</span>) =></span> {
<span class="hljs-keyword">const</span> { productId, quantity } = action.payload;
<span class="hljs-keyword">const</span> item = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (item) {
<span class="hljs-keyword">const</span> quantityDiff = quantity - item.quantity;
item.quantity = quantity; <span class="hljs-comment">// Update quantity</span>
state.total += item.price * quantityDiff; <span class="hljs-comment">// Update total</span>
}
}
}
});
<span class="hljs-comment">// Export action creators (automatically generated by createSlice)</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { addItem, removeItem, updateQuantity } = cartSlice.actions;
<span class="hljs-comment">// Create the store with configureStore</span>
<span class="hljs-keyword">const</span> store = configureStore({
<span class="hljs-attr">reducer</span>: {
<span class="hljs-attr">cart</span>: cartSlice.reducer, <span class="hljs-comment">// Add cart reducer to store</span>
<span class="hljs-comment">// You can add more reducers here</span>
}
});
<span class="hljs-comment">// Usage in components (same as regular Redux)</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ShoppingCart</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Note: state.cart because we named it 'cart' in configureStore</span>
<span class="hljs-keyword">const</span> { items, total } = useSelector(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.cart);
<span class="hljs-keyword">const</span> dispatch = useDispatch();
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h2</span>></span>Shopping Cart<span class="hljs-tag"></<span class="hljs-name">h2</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Total: ${total.toFixed(2)}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
{items.map(item => (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>{item.name} - Qty: {item.quantity}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> dispatch(removeItem(item.id))}>
Remove
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"><<span class="hljs-name">input</span>
<span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">{item.quantity}</span>
<span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> dispatch(updateQuantity({
productId: item.id,
quantity: parseInt(e.target.value)
}))}
/>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Redux Toolkit is better than vanilla Redux for a few key reasons:
-
Less boilerplate: No need to write action creators manually
-
Immer integration: Write code that looks like mutations but is actually immutable
-
Better defaults: configureStore includes useful middleware automatically
-
TypeScript friendly: Better type inference and support
-
DevTools included: Redux DevTools work automatically
Zustand: Simple and flexible state management
Zustand is a lightweight state management library that’s much simpler than Redux but more powerful than Context for complex state.
<span class="hljs-keyword">import</span> { create } <span class="hljs-keyword">from</span> <span class="hljs-string">'zustand'</span>;
<span class="hljs-comment">// Create a store with state and actions in one place</span>
<span class="hljs-keyword">const</span> useCartStore = create(<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-comment">// Initial state</span>
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-comment">// Actions (functions that update state)</span>
<span class="hljs-attr">addItem</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> {
<span class="hljs-keyword">const</span> existingItem = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === product.id);
<span class="hljs-keyword">if</span> (existingItem) {
<span class="hljs-comment">// Update existing item quantity</span>
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: state.items.map(<span class="hljs-function"><span class="hljs-params">item</span> =></span>
item.id === product.id
? { ...item, <span class="hljs-attr">quantity</span>: item.quantity + <span class="hljs-number">1</span> }
: item
),
<span class="hljs-attr">total</span>: state.total + product.price
};
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Add new item</span>
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: [...state.items, { ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: state.total + product.price
};
}
}),
<span class="hljs-attr">removeItem</span>: <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> {
<span class="hljs-keyword">const</span> itemToRemove = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (!itemToRemove) <span class="hljs-keyword">return</span> state;
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: state.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId),
<span class="hljs-attr">total</span>: state.total - (itemToRemove.price * itemToRemove.quantity)
};
}),
<span class="hljs-attr">clearCart</span>: <span class="hljs-function">() =></span> set({ <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> }),
<span class="hljs-comment">// Computed values (getters)</span>
<span class="hljs-keyword">get</span> <span class="hljs-title">itemCount</span>() {
<span class="hljs-keyword">return</span> get().items.reduce(<span class="hljs-function">(<span class="hljs-params">count, item</span>) =></span> count + item.quantity, <span class="hljs-number">0</span>);
}
}));
<span class="hljs-comment">// Usage in components - very clean</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductCard</span>(<span class="hljs-params">{ product }</span>) </span>{
<span class="hljs-comment">// Only get the function we need</span>
<span class="hljs-keyword">const</span> addItem = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.addItem);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product-card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>{product.name}<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>${product.price}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> addItem(product)}>
Add to Cart
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Only get the computed value we need</span>
<span class="hljs-keyword">const</span> itemCount = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.itemCount);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>
Cart ({itemCount})
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartList</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Get multiple values at once</span>
<span class="hljs-keyword">const</span> { items, total, removeItem } = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> ({
<span class="hljs-attr">items</span>: state.items,
<span class="hljs-attr">total</span>: state.total,
<span class="hljs-attr">removeItem</span>: state.removeItem
}));
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-list"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>Your Cart - Total: ${total.toFixed(2)}<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
{items.map(item => (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-item"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>{item.name} x {item.quantity}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> removeItem(item.id)}>
Remove
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
What makes Zustand special:
-
No boilerplate: Define state and actions in one place
-
No providers: No need to wrap your app in a Provider component
-
TypeScript friendly: Excellent TypeScript support out of the box
-
Small bundle: Much smaller than Redux
-
Simple mental model: Just hooks that return state and functions
Advanced Zustand patterns
Persistence and middleware:
<span class="hljs-keyword">import</span> { create } <span class="hljs-keyword">from</span> <span class="hljs-string">'zustand'</span>;
<span class="hljs-keyword">import</span> { persist, devtools } <span class="hljs-keyword">from</span> <span class="hljs-string">'zustand/middleware'</span>;
<span class="hljs-comment">// Store with localStorage persistence and Redux DevTools</span>
<span class="hljs-keyword">const</span> useCartStore = create(
devtools( <span class="hljs-comment">// Adds Redux DevTools support</span>
persist( <span class="hljs-comment">// Adds localStorage persistence</span>
<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">addItem</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(
<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">items</span>: [...state.items, { ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: state.total + product.price
}),
<span class="hljs-literal">false</span>, <span class="hljs-comment">// Don't replace entire state</span>
<span class="hljs-string">'cart/addItem'</span> <span class="hljs-comment">// Action name for dev tools</span>
),
<span class="hljs-attr">removeItem</span>: <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> set(
<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> {
<span class="hljs-keyword">const</span> itemToRemove = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: state.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId),
<span class="hljs-attr">total</span>: state.total - (itemToRemove?.price || <span class="hljs-number">0</span>)
};
},
<span class="hljs-literal">false</span>,
<span class="hljs-string">'cart/removeItem'</span>
)
}),
{
<span class="hljs-attr">name</span>: <span class="hljs-string">'cart-storage'</span>, <span class="hljs-comment">// localStorage key</span>
<span class="hljs-attr">getStorage</span>: <span class="hljs-function">() =></span> <span class="hljs-built_in">localStorage</span>, <span class="hljs-comment">// Storage method</span>
}
)
)
);
<span class="hljs-comment">// Subscriptions for side effects</span>
useCartStore.subscribe(
<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> state.items, <span class="hljs-comment">// Watch items array</span>
<span class="hljs-function">(<span class="hljs-params">items</span>) =></span> { <span class="hljs-comment">// Callback when items change</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Cart items updated:'</span>, items);
<span class="hljs-comment">// Update browser tab title</span>
<span class="hljs-built_in">document</span>.title = <span class="hljs-string">`Shopping (<span class="hljs-subst">${items.length}</span>) - MyStore`</span>;
<span class="hljs-comment">// Track analytics</span>
analytics.track(<span class="hljs-string">'Cart Updated'</span>, {
<span class="hljs-attr">itemCount</span>: items.length,
<span class="hljs-attr">cartValue</span>: items.reduce(<span class="hljs-function">(<span class="hljs-params">sum, item</span>) =></span> sum + item.price * item.quantity, <span class="hljs-number">0</span>)
});
}
);
Performance Optimization Strategies Explained
Shared state can cause performance issues when components re-render unnecessarily. Let’s understand why this happens and how to prevent it.
Why do unnecessary re-renders happen?
Here’s the fundamental issue: in React, when state changes, all components that use that state re-render, even if they don’t actually display the changed data.
<span class="hljs-comment">// Problem: This context causes ALL consumers to re-render when ANY value changes</span>
<span class="hljs-keyword">const</span> AppContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AppProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">email</span>: <span class="hljs-string">'alice@example.com'</span> });
<span class="hljs-keyword">const</span> [cart, setCart] = useState({ <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> });
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);
<span class="hljs-comment">// When ANY of these values change, ALL components using useContext(AppContext) re-render</span>
<span class="hljs-keyword">const</span> value = {
user, setUser,
cart, setCart,
theme, setTheme
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">AppContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">AppContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// This component only cares about theme, but re-renders when user or cart change</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeToggle</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { theme, setTheme } = useContext(AppContext); <span class="hljs-comment">// Gets ALL context data</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ThemeToggle rendering'</span>); <span class="hljs-comment">// This logs every time ANY context value changes</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span></span>
);
}
Solution 1: Split contexts to minimize re-renders
You can split large contexts into smaller, focused ones like this:
<span class="hljs-comment">// Instead of one large context, create separate contexts</span>
<span class="hljs-keyword">const</span> UserContext = createContext();
<span class="hljs-keyword">const</span> CartContext = createContext();
<span class="hljs-keyword">const</span> ThemeContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">email</span>: <span class="hljs-string">'alice@example.com'</span> });
<span class="hljs-comment">// Only components using UserContext re-render when user changes</span>
<span class="hljs-keyword">const</span> value = { user, setUser };
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">UserContext.Provider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);
<span class="hljs-comment">// Only components using ThemeContext re-render when theme changes</span>
<span class="hljs-keyword">const</span> value = { theme, setTheme };
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">ThemeContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Now ThemeToggle only re-renders when theme changes</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeToggle</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { theme, setTheme } = useContext(ThemeContext); <span class="hljs-comment">// Only theme data</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ThemeToggle rendering'</span>); <span class="hljs-comment">// Only logs when theme changes</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setTheme(theme === 'light' ? 'dark' : 'light')}>
Current theme: {theme}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span></span>
);
}
Solution 2: Memoize context values to prevent object recreation
The problem is that creating new objects in render causes unnecessary re-renders:
<span class="hljs-comment">// ❌ WRONG: Creates new objects every render</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [items, setItems] = useState([]);
<span class="hljs-keyword">const</span> [total, setTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
// <span class="hljs-attr">This</span> <span class="hljs-attr">creates</span> <span class="hljs-attr">a</span> <span class="hljs-attr">NEW</span> <span class="hljs-attr">object</span> <span class="hljs-attr">every</span> <span class="hljs-attr">time</span> <span class="hljs-attr">CartProvider</span> <span class="hljs-attr">renders</span>!
<span class="hljs-attr">items</span>, // <span class="hljs-attr">Same</span> <span class="hljs-attr">value</span>, <span class="hljs-attr">but</span> <span class="hljs-attr">new</span> <span class="hljs-attr">object</span> <span class="hljs-attr">reference</span>
<span class="hljs-attr">total</span>, // <span class="hljs-attr">Same</span> <span class="hljs-attr">value</span>, <span class="hljs-attr">but</span> <span class="hljs-attr">new</span> <span class="hljs-attr">object</span> <span class="hljs-attr">reference</span>
<span class="hljs-attr">addItem:</span> (<span class="hljs-attr">item</span>) =></span> { // NEW function every render!
setItems([...items, item]);
},
removeItem: (id) => { // NEW function every render!
setItems(items.filter(item => item.id !== id));
}
}}>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
This is bad because React uses Object.is()
to compare context values. Even if the data is the same, a new object means all consumers re-render.
<span class="hljs-comment">// ✅ CORRECT: Memoize the context value</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [items, setItems] = useState([]);
<span class="hljs-keyword">const</span> [total, setTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-comment">// useCallback memoizes functions - they only change when dependencies change</span>
<span class="hljs-keyword">const</span> addItem = useCallback(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prevItems</span> =></span> [...prevItems, item]); <span class="hljs-comment">// Use function update</span>
}, []); <span class="hljs-comment">// Empty dependency array means this function never changes</span>
<span class="hljs-keyword">const</span> removeItem = useCallback(<span class="hljs-function">(<span class="hljs-params">id</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prevItems</span> =></span> prevItems.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== id));
}, []);
<span class="hljs-comment">// useMemo memoizes the context value object</span>
<span class="hljs-keyword">const</span> value = useMemo(<span class="hljs-function">() =></span> ({
items,
total,
addItem,
removeItem
}), [items, total, addItem, removeItem]); <span class="hljs-comment">// Only create new object when these change</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
What useCallback and useMemo do:
-
useCallback(fn, deps): Returns a memoized function that only changes when dependencies change
-
useMemo(fn, deps): Returns a memoized value that only recalculates when dependencies change
Solution 3: Select only what you need
With Redux/Zustand, make sure you’re selective about what data you subscribe to:
<span class="hljs-comment">// ❌ WRONG: Component re-renders when ANY cart data changes</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { items, total, addItem, removeItem } = useCartStore(); <span class="hljs-comment">// Gets everything!</span>
<span class="hljs-comment">// This component only shows item count, but re-renders when total changes</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>
Cart ({items.length})
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// ✅ CORRECT: Only subscribe to what you need</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Only re-renders when items array changes</span>
<span class="hljs-keyword">const</span> itemCount = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.items.length);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>
Cart ({itemCount})
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// ✅ EVEN BETTER: Use a selector for computed values</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Only re-renders when the computed itemCount changes</span>
<span class="hljs-keyword">const</span> itemCount = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span>
state.items.reduce(<span class="hljs-function">(<span class="hljs-params">count, item</span>) =></span> count + item.quantity, <span class="hljs-number">0</span>)
);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>
Cart ({itemCount})
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Solution 4: Use React.memo for expensive components
React.memo prevents component re-renders when props haven’t changed:
<span class="hljs-comment">// Expensive component that does heavy calculations</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExpensiveProductList</span>(<span class="hljs-params">{ products, onAddToCart }</span>) </span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ExpensiveProductList rendering'</span>); <span class="hljs-comment">// This should log rarely</span>
<span class="hljs-comment">// Simulate expensive calculation</span>
<span class="hljs-keyword">const</span> processedProducts = products.map(<span class="hljs-function"><span class="hljs-params">product</span> =></span> ({
...product,
<span class="hljs-attr">discountedPrice</span>: product.price * <span class="hljs-number">0.9</span>,
<span class="hljs-attr">categories</span>: product.categories.sort(),
<span class="hljs-comment">// ... more expensive operations</span>
}));
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product-list"</span>></span>
{processedProducts.map(product => (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{product.id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>{product.name}<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Price: ${product.discountedPrice}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> onAddToCart(product)}>
Add to Cart
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// ❌ Without memo: Re-renders every time parent renders</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ExpensiveProductList;
<span class="hljs-comment">// ✅ With memo: Only re-renders when props actually change</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> React.memo(ExpensiveProductList);
<span class="hljs-comment">// ✅ With custom comparison: You control when it re-renders</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> React.memo(ExpensiveProductList, <span class="hljs-function">(<span class="hljs-params">prevProps, nextProps</span>) =></span> {
<span class="hljs-comment">// Return true if props are equal (skip re-render)</span>
<span class="hljs-comment">// Return false if props are different (re-render)</span>
<span class="hljs-keyword">return</span> (
prevProps.products.length === nextProps.products.length &&
prevProps.onAddToCart === nextProps.onAddToCart
);
});
Solution 5: Optimize with custom selector hooks
You can create reusable selector hooks for common patterns:
<span class="hljs-comment">// Custom hook that memoizes selectors</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCartSelector</span>(<span class="hljs-params">selector</span>) </span>{
<span class="hljs-keyword">const</span> selectedValue = useCartStore(selector);
<span class="hljs-comment">// The selector itself should be memoized to prevent unnecessary re-renders</span>
<span class="hljs-keyword">return</span> useMemo(<span class="hljs-function">() =></span> selectedValue, [selectedValue]);
}
<span class="hljs-comment">// Pre-defined selectors for common use cases</span>
<span class="hljs-keyword">const</span> selectItemCount = <span class="hljs-function">(<span class="hljs-params">state</span>) =></span> state.items.length;
<span class="hljs-keyword">const</span> selectTotal = <span class="hljs-function">(<span class="hljs-params">state</span>) =></span> state.total;
<span class="hljs-keyword">const</span> selectIsEmpty = <span class="hljs-function">(<span class="hljs-params">state</span>) =></span> state.items.length === <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> selectItemById = <span class="hljs-function">(<span class="hljs-params">id</span>) =></span> <span class="hljs-function">(<span class="hljs-params">state</span>) =></span> state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === id);
<span class="hljs-comment">// Usage in components</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartBadge</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> itemCount = useCartStore(selectItemCount); <span class="hljs-comment">// Only re-renders when count changes</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">span</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-badge"</span>></span>{itemCount}<span class="hljs-tag"></<span class="hljs-name">span</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartTotal</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> total = useCartStore(selectTotal); <span class="hljs-comment">// Only re-renders when total changes</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-total"</span>></span>
Total: ${total.toFixed(2)}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductInCart</span>(<span class="hljs-params">{ productId }</span>) </span>{
<span class="hljs-comment">// This selector is created with the specific productId</span>
<span class="hljs-keyword">const</span> selectThisItem = useMemo(
<span class="hljs-function">() =></span> <span class="hljs-function">(<span class="hljs-params">state</span>) =></span> state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId),
[productId]
);
<span class="hljs-keyword">const</span> item = useCartStore(selectThisItem);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
{item ? `In cart: ${item.quantity}` : 'Not in cart'}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Testing Shared State: A Comprehensive Approach
Testing shared state requires different approaches than testing isolated components. Let’s explore why this is more complex and what specific strategies we need.
Why shared state testing is different
When testing isolated components, you typically pass props directly to the component, mock external dependencies, and test the component’s output based on specific inputs.
But with shared state, you face additional challenges:
-
Dependencies on external state: Components depend on Context, Redux stores, or global state that must be provided
-
State synchronization: You need to test that multiple components stay in sync when state changes
-
Provider setup: Components using Context will crash without proper Provider wrappers
-
State mutations: Testing that state updates correctly across multiple components
-
Integration behavior: Ensuring the entire state management system works together
This means you’ll need different testing strategies. You’ll need to provide the correct state management infrastructure, test how changes in one component affect others, gracefully handle loading states, errors, and async operations, and test that optimizations work correctly.
Let’s explore each approach thoroughly.
Testing React Context
The challenge: Components using Context need a Provider to work, and you need to test both the Context logic and component behavior.
Why Context testing is unique: Unlike regular components that receive props directly, Context consumers depend on a Provider being present in the component tree. This creates several testing challenges:
-
Components will crash if used outside a Provider
-
Each test needs its own Provider instance to avoid test interference
-
You need to test that Provider and Consumer work together correctly
-
Testing
useContext
hooks requires special setup
Let’s see some strategies specific to Context.
Setting up Context tests:
<span class="hljs-keyword">import</span> { render, screen, fireEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> { createContext, useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-comment">// Our Context setup (same as before)</span>
<span class="hljs-keyword">const</span> CartContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCart</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> context = useContext(CartContext);
<span class="hljs-keyword">if</span> (context === <span class="hljs-literal">undefined</span>) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'useCart must be used within a CartProvider'</span>);
}
<span class="hljs-keyword">return</span> context;
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [items, setItems] = useState([]);
<span class="hljs-keyword">const</span> [total, setTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> addItem = <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prev</span> =></span> [...prev, product]);
setTotal(<span class="hljs-function"><span class="hljs-params">prev</span> =></span> prev + product.price);
};
<span class="hljs-keyword">const</span> removeItem = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prev</span> =></span> {
<span class="hljs-keyword">const</span> updatedItems = prev.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId);
<span class="hljs-keyword">const</span> removedItem = prev.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (removedItem) {
setTotal(<span class="hljs-function"><span class="hljs-params">current</span> =></span> current - removedItem.price);
}
<span class="hljs-keyword">return</span> updatedItems;
});
};
<span class="hljs-keyword">const</span> value = { items, total, addItem, removeItem };
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Test component that uses our Context</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TestCartComponent</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { items, total, addItem, removeItem } = useCart();
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">data-testid</span>=<span class="hljs-string">"item-count"</span>></span>{items.length}<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">data-testid</span>=<span class="hljs-string">"total"</span>></span>${total.toFixed(2)}<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span>
<span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> addItem({ id: 1, name: 'Test Product', price: 10 })}
data-testid="add-item"
>
Add Item
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
{items.map(item => (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span> <span class="hljs-attr">data-testid</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">item-</span>${<span class="hljs-attr">item.id</span>}`}></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>{item.name}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span>
<span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> removeItem(item.id)}
data-testid={`remove-${item.id}`}
>
Remove
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
))}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// Helper function to render components with CartProvider</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">renderWithCartProvider</span>(<span class="hljs-params">component</span>) </span>{
<span class="hljs-keyword">return</span> render(
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartProvider</span>></span>
{component}
<span class="hljs-tag"></<span class="hljs-name">CartProvider</span>></span></span>
);
}
Writing Context tests:
describe(<span class="hljs-string">'Cart Context functionality'</span>, <span class="hljs-function">() =></span> {
test(<span class="hljs-string">'should start with empty cart'</span>, <span class="hljs-function">() =></span> {
renderWithCartProvider(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span></span>);
<span class="hljs-comment">// Check initial state</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'0'</span>);
expect(screen.getByTestId(<span class="hljs-string">'total'</span>)).toHaveTextContent(<span class="hljs-string">'$0.00'</span>);
});
test(<span class="hljs-string">'should add item to cart'</span>, <span class="hljs-function">() =></span> {
renderWithCartProvider(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span></span>);
<span class="hljs-comment">// Click the add button</span>
<span class="hljs-keyword">const</span> addButton = screen.getByTestId(<span class="hljs-string">'add-item'</span>);
fireEvent.click(addButton);
<span class="hljs-comment">// Verify item was added</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'1'</span>);
expect(screen.getByTestId(<span class="hljs-string">'total'</span>)).toHaveTextContent(<span class="hljs-string">'$10.00'</span>);
expect(screen.getByTestId(<span class="hljs-string">'item-1'</span>)).toBeInTheDocument();
expect(screen.getByText(<span class="hljs-string">'Test Product'</span>)).toBeInTheDocument();
});
test(<span class="hljs-string">'should remove item from cart'</span>, <span class="hljs-function">() =></span> {
renderWithCartProvider(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span></span>);
<span class="hljs-comment">// Add item first</span>
fireEvent.click(screen.getByTestId(<span class="hljs-string">'add-item'</span>));
<span class="hljs-comment">// Verify item is there</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'1'</span>);
<span class="hljs-comment">// Remove the item</span>
fireEvent.click(screen.getByTestId(<span class="hljs-string">'remove-1'</span>));
<span class="hljs-comment">// Verify item was removed</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'0'</span>);
expect(screen.getByTestId(<span class="hljs-string">'total'</span>)).toHaveTextContent(<span class="hljs-string">'$0.00'</span>);
expect(screen.queryByTestId(<span class="hljs-string">'item-1'</span>)).not.toBeInTheDocument();
});
test(<span class="hljs-string">'should handle multiple items'</span>, <span class="hljs-function">() =></span> {
renderWithCartProvider(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span></span>);
<span class="hljs-comment">// Add multiple items</span>
fireEvent.click(screen.getByTestId(<span class="hljs-string">'add-item'</span>));
fireEvent.click(screen.getByTestId(<span class="hljs-string">'add-item'</span>));
fireEvent.click(screen.getByTestId(<span class="hljs-string">'add-item'</span>));
<span class="hljs-comment">// Verify count and total</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'3'</span>);
expect(screen.getByTestId(<span class="hljs-string">'total'</span>)).toHaveTextContent(<span class="hljs-string">'$30.00'</span>);
});
test(<span class="hljs-string">'should throw error when used outside provider'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Mock console.error to avoid error output in tests</span>
<span class="hljs-keyword">const</span> consoleSpy = jest.spyOn(<span class="hljs-built_in">console</span>, <span class="hljs-string">'error'</span>).mockImplementation(<span class="hljs-function">() =></span> {});
<span class="hljs-comment">// This should throw an error</span>
expect(<span class="hljs-function">() =></span> {
render(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span></span>); <span class="hljs-comment">// No CartProvider wrapper</span>
}).toThrow(<span class="hljs-string">'useCart must be used within a CartProvider'</span>);
consoleSpy.mockRestore();
});
test(<span class="hljs-string">'should handle edge cases'</span>, <span class="hljs-function">() =></span> {
renderWithCartProvider(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span></span>);
<span class="hljs-comment">// Try to remove item that doesn't exist</span>
<span class="hljs-keyword">const</span> initialCount = screen.getByTestId(<span class="hljs-string">'item-count'</span>).textContent;
<span class="hljs-comment">// This shouldn't crash or change anything</span>
fireEvent.click(screen.getByTestId(<span class="hljs-string">'add-item'</span>));
fireEvent.click(screen.getByTestId(<span class="hljs-string">'remove-999'</span>)); <span class="hljs-comment">// Non-existent item</span>
<span class="hljs-comment">// Count should still be 1</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'1'</span>);
});
});
Testing Context with different initial states:
<span class="hljs-comment">// Custom Provider for testing with specific initial state</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TestCartProvider</span>(<span class="hljs-params">{ children, initialItems = [], initialTotal = <span class="hljs-number">0</span> }</span>) </span>{
<span class="hljs-keyword">const</span> [items, setItems] = useState(initialItems);
<span class="hljs-keyword">const</span> [total, setTotal] = useState(initialTotal);
<span class="hljs-comment">// Same logic as CartProvider</span>
<span class="hljs-keyword">const</span> addItem = <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prev</span> =></span> [...prev, product]);
setTotal(<span class="hljs-function"><span class="hljs-params">prev</span> =></span> prev + product.price);
};
<span class="hljs-keyword">const</span> removeItem = <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prev</span> =></span> {
<span class="hljs-keyword">const</span> updatedItems = prev.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId);
<span class="hljs-keyword">const</span> removedItem = prev.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (removedItem) {
setTotal(<span class="hljs-function"><span class="hljs-params">current</span> =></span> current - removedItem.price);
}
<span class="hljs-keyword">return</span> updatedItems;
});
};
<span class="hljs-keyword">const</span> value = { items, total, addItem, removeItem };
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
describe(<span class="hljs-string">'Cart Context with initial state'</span>, <span class="hljs-function">() =></span> {
test(<span class="hljs-string">'should work with pre-populated cart'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> initialItems = [
{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Existing Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">15</span> },
{ <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Another Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">25</span> }
];
render(
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">TestCartProvider</span> <span class="hljs-attr">initialItems</span>=<span class="hljs-string">{initialItems}</span> <span class="hljs-attr">initialTotal</span>=<span class="hljs-string">{40}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">TestCartComponent</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">TestCartProvider</span>></span></span>
);
<span class="hljs-comment">// Should show existing items</span>
expect(screen.getByTestId(<span class="hljs-string">'item-count'</span>)).toHaveTextContent(<span class="hljs-string">'2'</span>);
expect(screen.getByTestId(<span class="hljs-string">'total'</span>)).toHaveTextContent(<span class="hljs-string">'$40.00'</span>);
expect(screen.getByText(<span class="hljs-string">'Existing Product'</span>)).toBeInTheDocument();
expect(screen.getByText(<span class="hljs-string">'Another Product'</span>)).toBeInTheDocument();
});
});
Testing Redux stores
Why Redux testing requires different approaches: Redux introduces a predictable but complex state management system that needs testing at multiple levels:
-
Pure function testing: Reducers are pure functions that can be tested in isolation
-
Action creator testing: Ensuring actions are created correctly
-
Connected component testing: Components that use
useSelector
anduseDispatch
need store setup -
Integration testing: Testing the entire Redux flow from action dispatch to state update to component re-render
-
Async action testing: Testing thunks, sagas, or other async middleware
Redux testing focuses on three areas: action creators, reducers, and connected components.
Testing reducers (pure functions):
<span class="hljs-keyword">import</span> cartReducer, { addItem, removeItem, updateQuantity } <span class="hljs-keyword">from</span> <span class="hljs-string">'./cartSlice'</span>;
describe(<span class="hljs-string">'Cart reducer'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> initialState = {
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>
};
test(<span class="hljs-string">'should return initial state when called with undefined'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-comment">// Reducer should handle undefined state</span>
<span class="hljs-keyword">const</span> result = cartReducer(<span class="hljs-literal">undefined</span>, { <span class="hljs-attr">type</span>: <span class="hljs-string">'unknown'</span> });
expect(result).toEqual(initialState);
});
test(<span class="hljs-string">'should handle addItem action'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> product = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span> };
<span class="hljs-keyword">const</span> action = addItem(product);
<span class="hljs-keyword">const</span> result = cartReducer(initialState, action);
expect(result).toEqual({
<span class="hljs-attr">items</span>: [{ ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">10</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">1</span>
});
<span class="hljs-comment">// Original state should be unchanged (immutability test)</span>
expect(initialState.items).toHaveLength(<span class="hljs-number">0</span>);
});
test(<span class="hljs-string">'should increase quantity for existing item'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> existingState = {
<span class="hljs-attr">items</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">10</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">1</span>
};
<span class="hljs-keyword">const</span> product = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span> };
<span class="hljs-keyword">const</span> action = addItem(product);
<span class="hljs-keyword">const</span> result = cartReducer(existingState, action);
expect(result).toEqual({
<span class="hljs-attr">items</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">2</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">20</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">2</span>
});
});
test(<span class="hljs-string">'should handle removeItem action'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> existingState = {
<span class="hljs-attr">items</span>: [
{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Product 1'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">2</span> },
{ <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Product 2'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">15</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }
],
<span class="hljs-attr">total</span>: <span class="hljs-number">35</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">3</span>
};
<span class="hljs-keyword">const</span> action = removeItem(<span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> result = cartReducer(existingState, action);
expect(result).toEqual({
<span class="hljs-attr">items</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Product 2'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">15</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">15</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">1</span>
});
});
test(<span class="hljs-string">'should handle updateQuantity action'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> existingState = {
<span class="hljs-attr">items</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">2</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">20</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">2</span>
};
<span class="hljs-keyword">const</span> action = updateQuantity({ <span class="hljs-attr">productId</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">5</span> });
<span class="hljs-keyword">const</span> result = cartReducer(existingState, action);
expect(result).toEqual({
<span class="hljs-attr">items</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">5</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">50</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">5</span>
});
});
test(<span class="hljs-string">'should remove item when quantity is set to 0'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> existingState = {
<span class="hljs-attr">items</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">2</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">20</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">2</span>
};
<span class="hljs-keyword">const</span> action = updateQuantity({ <span class="hljs-attr">productId</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">0</span> });
<span class="hljs-keyword">const</span> result = cartReducer(existingState, action);
expect(result).toEqual({
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>
});
});
});
Testing Redux-connected components:
<span class="hljs-keyword">import</span> { render, screen, fireEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> { configureStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'@reduxjs/toolkit'</span>;
<span class="hljs-keyword">import</span> cartReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./cartSlice'</span>;
<span class="hljs-keyword">import</span> ConnectedProductCard <span class="hljs-keyword">from</span> <span class="hljs-string">'./ProductCard'</span>;
<span class="hljs-comment">// Helper to create a test store with initial state</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createTestStore</span>(<span class="hljs-params">initialState = {}</span>) </span>{
<span class="hljs-keyword">return</span> configureStore({
<span class="hljs-attr">reducer</span>: {
<span class="hljs-attr">cart</span>: cartReducer
},
<span class="hljs-attr">preloadedState</span>: {
<span class="hljs-attr">cart</span>: {
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>,
...initialState
}
}
});
}
<span class="hljs-comment">// Helper to render components with Redux store</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">renderWithStore</span>(<span class="hljs-params">component, store</span>) </span>{
<span class="hljs-keyword">return</span> render(
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>></span>
{component}
<span class="hljs-tag"></<span class="hljs-name">Provider</span>></span></span>
);
}
describe(<span class="hljs-string">'ConnectedProductCard'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> mockProduct = {
<span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>,
<span class="hljs-attr">price</span>: <span class="hljs-number">25</span>,
<span class="hljs-attr">description</span>: <span class="hljs-string">'A test product'</span>
};
test(<span class="hljs-string">'should display product information'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> store = createTestStore();
renderWithStore(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ConnectedProductCard</span> <span class="hljs-attr">product</span>=<span class="hljs-string">{mockProduct}</span> /></span></span>, store);
expect(screen.getByText(<span class="hljs-string">'Test Product'</span>)).toBeInTheDocument();
expect(screen.getByText(<span class="hljs-string">'$25'</span>)).toBeInTheDocument();
expect(screen.getByText(<span class="hljs-string">'A test product'</span>)).toBeInTheDocument();
});
test(<span class="hljs-string">'should add item to cart when button clicked'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> store = createTestStore();
renderWithStore(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ConnectedProductCard</span> <span class="hljs-attr">product</span>=<span class="hljs-string">{mockProduct}</span> /></span></span>, store);
<span class="hljs-comment">// Initially, cart should be empty</span>
expect(store.getState().cart.items).toHaveLength(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Click add to cart button</span>
fireEvent.click(screen.getByRole(<span class="hljs-string">'button'</span>, { <span class="hljs-attr">name</span>: <span class="hljs-regexp">/add to cart/i</span> }));
<span class="hljs-comment">// Check that item was added to store</span>
<span class="hljs-keyword">const</span> cartState = store.getState().cart;
expect(cartState.items).toHaveLength(<span class="hljs-number">1</span>);
expect(cartState.items[<span class="hljs-number">0</span>]).toEqual({ ...mockProduct, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> });
expect(cartState.total).toBe(<span class="hljs-number">25</span>);
});
test(<span class="hljs-string">'should show "In Cart" when item is already in cart'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> store = createTestStore({
<span class="hljs-attr">items</span>: [{ ...mockProduct, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: <span class="hljs-number">25</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">1</span>
});
renderWithStore(<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ConnectedProductCard</span> <span class="hljs-attr">product</span>=<span class="hljs-string">{mockProduct}</span> /></span></span>, store);
<span class="hljs-comment">// Button should be disabled and show "In Cart"</span>
<span class="hljs-keyword">const</span> button = screen.getByRole(<span class="hljs-string">'button'</span>);
expect(button).toBeDisabled();
expect(button).toHaveTextContent(<span class="hljs-string">'In Cart'</span>);
});
});
Integration testing with multiple connected components:
<span class="hljs-keyword">import</span> { render, screen, fireEvent } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> { createTestStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'./test-utils'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>;
describe(<span class="hljs-string">'Cart integration'</span>, <span class="hljs-function">() =></span> {
test(<span class="hljs-string">'should update cart badge when item is added'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> store = createTestStore();
render(
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">App</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Provider</span>></span></span>
);
<span class="hljs-comment">// Initially, no cart badge should be visible</span>
expect(screen.queryByText(<span class="hljs-regexp">/cart (/</span>)).not.toBeInTheDocument();
<span class="hljs-comment">// Add a product to cart</span>
<span class="hljs-keyword">const</span> addButton = screen.getByRole(<span class="hljs-string">'button'</span>, { <span class="hljs-attr">name</span>: <span class="hljs-regexp">/add to cart/i</span> });
fireEvent.click(addButton);
<span class="hljs-comment">// Cart badge should now show 1 item</span>
expect(screen.getByText(<span class="hljs-string">'Cart (1)'</span>)).toBeInTheDocument();
});
test(<span class="hljs-string">'should show cart items when cart dropdown is opened'</span>, <span class="hljs-keyword">async</span> () => {
<span class="hljs-keyword">const</span> store = createTestStore({
<span class="hljs-attr">items</span>: [
{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }
],
<span class="hljs-attr">total</span>: <span class="hljs-number">10</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">1</span>
});
render(
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">App</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Provider</span>></span></span>
);
<span class="hljs-comment">// Open cart dropdown</span>
fireEvent.click(screen.getByRole(<span class="hljs-string">'button'</span>, { <span class="hljs-attr">name</span>: <span class="hljs-regexp">/cart/i</span> }));
<span class="hljs-comment">// Should show cart item</span>
expect(screen.getByText(<span class="hljs-string">'Test Product'</span>)).toBeInTheDocument();
expect(screen.getByText(<span class="hljs-string">'$10.00'</span>)).toBeInTheDocument();
});
test(<span class="hljs-string">'should remove item when remove button is clicked'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> store = createTestStore({
<span class="hljs-attr">items</span>: [
{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }
],
<span class="hljs-attr">total</span>: <span class="hljs-number">10</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">1</span>
});
render(
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">App</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Provider</span>></span></span>
);
<span class="hljs-comment">// Open cart dropdown</span>
fireEvent.click(screen.getByRole(<span class="hljs-string">'button'</span>, { <span class="hljs-attr">name</span>: <span class="hljs-regexp">/cart/i</span> }));
<span class="hljs-comment">// Remove the item</span>
fireEvent.click(screen.getByRole(<span class="hljs-string">'button'</span>, { <span class="hljs-attr">name</span>: <span class="hljs-regexp">/remove/i</span> }));
<span class="hljs-comment">// Item should be gone</span>
expect(screen.queryByText(<span class="hljs-string">'Test Product'</span>)).not.toBeInTheDocument();
<span class="hljs-comment">// Cart badge should be gone</span>
expect(screen.queryByText(<span class="hljs-regexp">/cart (/</span>)).not.toBeInTheDocument();
});
});
Testing custom hooks for state management:
Why custom hook testing is unique: Custom hooks can’t be tested like regular functions because they use React hooks internally, which can only be called within React components. This creates specific testing challenges:
-
React context requirement: Hooks must be called within a React component or test environment
-
State persistence: Testing that state persists correctly between renders
-
Effect testing: Testing useEffect cleanup and dependency changes
-
Isolation: Testing hook logic separately from UI components
-
Multiple render cycles: Testing how hooks behave across re-renders
You’ll need some special testing utilities:
-
renderHook()
: Renders a hook in a test component -
act()
: Ensures state updates are processed before assertions -
Mock timers for testing delayed effects
<span class="hljs-keyword">import</span> { renderHook, act } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> { useCart } <span class="hljs-keyword">from</span> <span class="hljs-string">'./useCart'</span>;
describe(<span class="hljs-string">'useCart hook'</span>, <span class="hljs-function">() =></span> {
test(<span class="hljs-string">'should initialize with empty cart'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =></span> useCart());
expect(result.current.items).toEqual([]);
expect(result.current.total).toBe(<span class="hljs-number">0</span>);
expect(result.current.itemCount).toBe(<span class="hljs-number">0</span>);
});
test(<span class="hljs-string">'should add item to cart'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =></span> useCart());
<span class="hljs-keyword">const</span> product = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span> };
act(<span class="hljs-function">() =></span> {
result.current.addItem(product);
});
expect(result.current.items).toHaveLength(<span class="hljs-number">1</span>);
expect(result.current.items[<span class="hljs-number">0</span>]).toEqual({ ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> });
expect(result.current.total).toBe(<span class="hljs-number">10</span>);
expect(result.current.itemCount).toBe(<span class="hljs-number">1</span>);
});
test(<span class="hljs-string">'should remove item from cart'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =></span> useCart());
<span class="hljs-keyword">const</span> product = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Test Product'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span> };
<span class="hljs-comment">// Add item first</span>
act(<span class="hljs-function">() =></span> {
result.current.addItem(product);
});
<span class="hljs-comment">// Then remove it</span>
act(<span class="hljs-function">() =></span> {
result.current.removeItem(<span class="hljs-number">1</span>);
});
expect(result.current.items).toHaveLength(<span class="hljs-number">0</span>);
expect(result.current.total).toBe(<span class="hljs-number">0</span>);
expect(result.current.itemCount).toBe(<span class="hljs-number">0</span>);
});
test(<span class="hljs-string">'should handle multiple items'</span>, <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> { result } = renderHook(<span class="hljs-function">() =></span> useCart());
<span class="hljs-keyword">const</span> product1 = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Product 1'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">10</span> };
<span class="hljs-keyword">const</span> product2 = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Product 2'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">15</span> };
act(<span class="hljs-function">() =></span> {
result.current.addItem(product1);
result.current.addItem(product2);
});
expect(result.current.items).toHaveLength(<span class="hljs-number">2</span>);
expect(result.current.total).toBe(<span class="hljs-number">25</span>);
expect(result.current.itemCount).toBe(<span class="hljs-number">2</span>);
});
});
When to Use Each Approach: A Decision Framework
Choosing the right state management approach is crucial for maintainable applications. Here’s how to decide:
Decision tree for state management
1. Is the state only needed by one component and its direct children? → Use local state with useState:
<span class="hljs-comment">// Good for: Form inputs, toggles, local UI state</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ContactForm</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>); <span class="hljs-comment">// Only this form needs it</span>
<span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>); <span class="hljs-comment">// Only this form needs it</span>
<span class="hljs-keyword">const</span> [isSubmitting, setIsSubmitting] = useState(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Only this form needs it</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">form</span>></span>
<span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setName(e.target.value)} />
<span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setEmail(e.target.value)} />
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{isSubmitting}</span>></span>Submit<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">form</span>></span></span>
);
}
2. Do 3-5 components need the same data, and it doesn’t change frequently? → Use React Context:
<span class="hljs-comment">// Good for: User authentication, theme settings, language preferences</span>
<span class="hljs-keyword">const</span> ThemeContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>); <span class="hljs-comment">// Changes rarely</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">theme</span>, <span class="hljs-attr">setTheme</span> }}></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">ThemeContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Used by Header, Sidebar, Settings components</span>
3. Do many unrelated components need the same data that changes frequently? → Use a state management library (Redux, Zustand):
<span class="hljs-comment">// Good for: Shopping cart, complex forms, real-time data</span>
<span class="hljs-keyword">const</span> useCartStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">addItem</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">items</span>: [...state.items, product],
<span class="hljs-attr">total</span>: state.total + product.price
}))
}));
<span class="hljs-comment">// Used by ProductCard, CartBadge, CartSidebar, Checkout, etc.</span>
4. Do you need to encapsulate reusable logic across multiple components? → Create custom hooks:
<span class="hljs-comment">// Good for: API calls, form validation, complex calculations</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useApi</span>(<span class="hljs-params">url</span>) </span>{
<span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);
<span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);
useEffect(<span class="hljs-function">() =></span> {
fetch(url)
.then(<span class="hljs-function"><span class="hljs-params">response</span> =></span> response.json())
.then(setData)
.catch(setError)
.finally(<span class="hljs-function">() =></span> setLoading(<span class="hljs-literal">false</span>));
}, [url]);
<span class="hljs-keyword">return</span> { data, loading, error };
}
<span class="hljs-comment">// Reusable across any component that needs API data</span>
Detailed comparison of approaches
Here’s a helpful table that lays out each approach along with their best use cases, pros, and cons:
Approach | Best For | Pros | Cons | Learning Curve |
Local State | Form inputs, UI toggles, component-specific data | Simple, fast, built-in | Limited scope, prop drilling | Easy |
Context | Theme, auth, moderate shared state | No prop drilling, built-in | Can cause re-renders, not great for frequent updates | Medium |
Redux | Complex state, time-travel debugging, large teams | Predictable, great DevTools, scalable | Lots of boilerplate, learning curve | Hard |
Redux Toolkit | Modern Redux projects | Less boilerplate than Redux, good patterns | Still complex, opinionated | Medium-Hard |
Zustand | Simple global state, modern projects | Minimal boilerplate, TypeScript friendly, small | Less ecosystem, newer library | Easy-Medium |
Custom Hooks | Reusable logic, moderate complexity | Composable, reusable, testable | Can get complex, need good patterns | Medium |
Real-world examples of when to use each
Local State Examples
Local state excels when data is temporary, component-specific, and doesn’t need to be shared. It provides the fastest performance and simplest code because there’s no overhead of state management systems.
<span class="hljs-comment">// ✅ Perfect for local state</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ImageGallery</span>(<span class="hljs-params">{ images }</span>) </span>{
<span class="hljs-keyword">const</span> [currentIndex, setCurrentIndex] = useState(<span class="hljs-number">0</span>); <span class="hljs-comment">// Only this component cares</span>
<span class="hljs-keyword">const</span> [isFullscreen, setIsFullscreen] = useState(<span class="hljs-literal">false</span>); <span class="hljs-comment">// Only this component cares</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"gallery"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{images[currentIndex]}</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setCurrentIndex(currentIndex + 1)}>Next<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setIsFullscreen(true)}>Fullscreen<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-comment">// ✅ Good for forms</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LoginForm</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> [errors, setErrors] = useState({});
<span class="hljs-comment">// All this state is specific to this form</span>
}
Local state works here because:
-
State is contained within the component that uses it
-
No external subscriptions or providers are needed
-
It’s easy to reason about and test
-
State automatically clears when component unmounts
-
Component is self-contained and reusable
Context Examples
Context works best for stable data that many components need but changes infrequently. It eliminates prop drilling while avoiding the complexity of full state management libraries.
<span class="hljs-comment">// ✅ Perfect for Context - used by many components, changes rarely</span>
<span class="hljs-keyword">const</span> AuthContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AuthProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> [isLoggedIn, setIsLoggedIn] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Authentication status doesn't change frequently</span>
<span class="hljs-comment">// Many components need to know if user is logged in</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">AuthContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">user</span>, <span class="hljs-attr">isLoggedIn</span>, <span class="hljs-attr">setUser</span>, <span class="hljs-attr">setIsLoggedIn</span> }}></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">AuthContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// ✅ Good for theme settings</span>
<span class="hljs-keyword">const</span> ThemeContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);
<span class="hljs-keyword">const</span> [fontSize, setFontSize] = useState(<span class="hljs-string">'medium'</span>);
<span class="hljs-comment">// Theme changes rarely but affects many components</span>
}
Context excels here because:
-
Wide reach, stable data: Many components need this information, but it doesn’t change often
-
Built-in solution: No external dependencies required
-
Automatic updates: All consumers automatically re-render when the context changes
-
Clear boundaries: Easy to understand what components have access to the data
-
Reasonable complexity: More complex than local state but much simpler than Redux
When Context struggles:
-
Frequent updates: Every context change causes all consumers to re-render
-
Complex state logic: Multiple related pieces of state become unwieldy
-
Performance critical: Large numbers of consumers can cause performance issues
Redux/Zustand Examples
These libraries shine when you have a complex, interconnected state that changes frequently and needs to be accessed by many unrelated components. They provide predictable updates, debugging tools, and performance optimizations.
<span class="hljs-comment">// ✅ Perfect for Redux/Zustand - complex state, many components, frequent updates</span>
<span class="hljs-keyword">const</span> useShoppingStore = create(<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-comment">// Cart data</span>
<span class="hljs-attr">cart</span>: { <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> },
<span class="hljs-comment">// User data </span>
<span class="hljs-attr">user</span>: { <span class="hljs-attr">profile</span>: <span class="hljs-literal">null</span>, <span class="hljs-attr">preferences</span>: {} },
<span class="hljs-comment">// UI state</span>
<span class="hljs-attr">ui</span>: {
<span class="hljs-attr">sidebarOpen</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">currentPage</span>: <span class="hljs-string">'home'</span>,
<span class="hljs-attr">notifications</span>: []
},
<span class="hljs-comment">// Many actions that update different parts of state</span>
<span class="hljs-attr">addToCart</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">cart</span>: {
<span class="hljs-attr">items</span>: [...state.cart.items, product],
<span class="hljs-attr">total</span>: state.cart.total + product.price
}
})),
<span class="hljs-attr">updateUserProfile</span>: <span class="hljs-function">(<span class="hljs-params">profile</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">user</span>: { ...state.user, profile }
})),
<span class="hljs-attr">showNotification</span>: <span class="hljs-function">(<span class="hljs-params">message</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">ui</span>: {
...state.ui,
<span class="hljs-attr">notifications</span>: [...state.ui.notifications, { <span class="hljs-attr">id</span>: <span class="hljs-built_in">Date</span>.now(), message }]
}
}))
}));
<span class="hljs-comment">// Used by: ProductCard, CartBadge, UserProfile, Sidebar, Notifications, etc.</span>
Why state management libraries excel here:
-
Centralized logic: All state changes go through predictable update mechanisms
-
Performance optimization: Libraries provide selector-based subscriptions to minimize re-renders
-
Debugging tools: Redux DevTools, time-travel debugging, action tracking
-
Scalability: Can handle complex state relationships and async operations
-
Team consistency: Established patterns that multiple developers can follow
-
Middleware support: Logging, persistence, error handling can be added systematically
Redux is best for large teams, complex async flows, need for strict predictability. Zustand is best for modern apps that want Redux benefits without boilerplate. And Recoil/Jotai is best for fine-grained reactive updates and complex dependencies.
Custom Hook Examples
Custom hooks excel when you have stateful logic that multiple components need, but the logic itself is more important than the data. They provide composition and reusability while keeping complexity contained.
<span class="hljs-comment">// ✅ Perfect for custom hooks - reusable logic</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useLocalStorage</span>(<span class="hljs-params">key, initialValue</span>) </span>{
<span class="hljs-keyword">const</span> [storedValue, setStoredValue] = useState(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> item = <span class="hljs-built_in">window</span>.localStorage.getItem(key);
<span class="hljs-keyword">return</span> item ? <span class="hljs-built_in">JSON</span>.parse(item) : initialValue;
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-keyword">return</span> initialValue;
}
});
<span class="hljs-keyword">const</span> setValue = <span class="hljs-function">(<span class="hljs-params">value</span>) =></span> {
<span class="hljs-keyword">try</span> {
setStoredValue(value);
<span class="hljs-built_in">window</span>.localStorage.setItem(key, <span class="hljs-built_in">JSON</span>.stringify(value));
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error saving to localStorage:'</span>, error);
}
};
<span class="hljs-keyword">return</span> [storedValue, setValue];
}
<span class="hljs-comment">// ✅ Reusable API logic</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useApi</span>(<span class="hljs-params">url</span>) </span>{
<span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> [loading, setLoading] = useState(<span class="hljs-literal">true</span>);
<span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-literal">null</span>);
useEffect(<span class="hljs-function">() =></span> {
<span class="hljs-keyword">let</span> cancelled = <span class="hljs-literal">false</span>;
fetch(url)
.then(<span class="hljs-function"><span class="hljs-params">response</span> =></span> {
<span class="hljs-keyword">if</span> (!response.ok) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Network response was not ok'</span>);
<span class="hljs-keyword">return</span> response.json();
})
.then(<span class="hljs-function"><span class="hljs-params">data</span> =></span> {
<span class="hljs-keyword">if</span> (!cancelled) {
setData(data);
setLoading(<span class="hljs-literal">false</span>);
}
})
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =></span> {
<span class="hljs-keyword">if</span> (!cancelled) {
setError(error);
setLoading(<span class="hljs-literal">false</span>);
}
});
<span class="hljs-keyword">return</span> <span class="hljs-function">() =></span> { cancelled = <span class="hljs-literal">true</span>; };
}, [url]);
<span class="hljs-keyword">return</span> { data, loading, error };
}
<span class="hljs-comment">// Can be used in any component that needs API data</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">{ userId }</span>) </span>{
<span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: user, loading, error } = useApi(<span class="hljs-string">`/api/users/<span class="hljs-subst">${userId}</span>`</span>);
<span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>Loading...<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
<span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>Error: {error.message}<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>Welcome, {user.name}!<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
}
Why custom hooks are perfect here:
-
Logic reusability: Same stateful behavior can be used across multiple components
-
Composition: Hooks can be combined and built upon each other
-
Separation of concerns: Business logic is separated from UI rendering
-
Testability: Logic can be tested independently of components
-
Flexibility: Each component can use the hook differently while sharing core logic
-
No provider overhead: Unlike Context, no wrapper components needed
When custom hooks work best:
-
Cross-cutting concerns: Authentication, API calls, form validation, local storage
-
Complex calculations: Data processing that multiple components need
-
Third-party integrations: Wrapping external libraries with React-friendly interfaces
-
Stateful behavior: Managing complex state machines or multi-step processes
Common Pitfalls and How to Avoid Them
Understanding common mistakes helps you write better, more maintainable code.
Pitfall 1: Context hell (too many nested providers)
The Problem:
<span class="hljs-comment">// ❌ WRONG: Too many nested providers make code hard to read and maintain</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">ThemeProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">CartProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">NotificationProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">AnalyticsProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">FeatureFlagProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">LocaleProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Router</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Routes</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Router</span>></span>
<span class="hljs-tag"></<span class="hljs-name">LocaleProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">FeatureFlagProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">AnalyticsProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">NotificationProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">CartProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">ThemeProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">UserProvider</span>></span></span>
);
}
Why this is bad:
-
Hard to read and understand the component hierarchy
-
Difficult to reorder or remove providers
-
Each level of nesting adds complexity
-
Testing becomes difficult with so many providers
Solution 1: Combine related providers
<span class="hljs-comment">// ✅ BETTER: Group related providers together</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AppProviders</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">ThemeProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">LocaleProvider</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">LocaleProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">ThemeProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">UserProvider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ShoppingProviders</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">NotificationProvider</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">NotificationProvider</span>></span>
<span class="hljs-tag"></<span class="hljs-name">CartProvider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">AppProviders</span>></span>
<span class="hljs-tag"><<span class="hljs-name">ShoppingProviders</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Router</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Routes</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Router</span>></span>
<span class="hljs-tag"></<span class="hljs-name">ShoppingProviders</span>></span>
<span class="hljs-tag"></<span class="hljs-name">AppProviders</span>></span></span>
);
}
Solution 2: Use a state management library instead
<span class="hljs-comment">// ✅ EVEN BETTER: Use Zustand or Redux for complex state</span>
<span class="hljs-keyword">const</span> useAppStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">theme</span>: <span class="hljs-string">'light'</span>,
<span class="hljs-attr">cart</span>: { <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> },
<span class="hljs-attr">notifications</span>: [],
<span class="hljs-comment">// All actions in one place</span>
<span class="hljs-attr">setUser</span>: <span class="hljs-function">(<span class="hljs-params">user</span>) =></span> set({ user }),
<span class="hljs-attr">setTheme</span>: <span class="hljs-function">(<span class="hljs-params">theme</span>) =></span> set({ theme }),
<span class="hljs-attr">addToCart</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">cart</span>: {
<span class="hljs-attr">items</span>: [...state.cart.items, product],
<span class="hljs-attr">total</span>: state.cart.total + product.price
}
})),
<span class="hljs-attr">addNotification</span>: <span class="hljs-function">(<span class="hljs-params">notification</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">notifications</span>: [...state.notifications, notification]
}))
}));
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// No providers needed! Just use the store directly</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">Router</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Routes</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Router</span>></span></span>
);
}
Pitfall 2: Massive context values causing unnecessary re-renders
The Problem:
<span class="hljs-comment">// ❌ WRONG: Putting everything in one context causes all components to re-render</span>
<span class="hljs-keyword">const</span> AppContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AppProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> [cart, setCart] = useState({ <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> });
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);
<span class="hljs-keyword">const</span> [notifications, setNotifications] = useState([]);
<span class="hljs-keyword">const</span> [products, setProducts] = useState([]);
<span class="hljs-keyword">const</span> [orders, setOrders] = useState([]);
<span class="hljs-comment">// ... 15 more pieces of state</span>
<span class="hljs-comment">// Every time ANY state changes, ALL components re-render!</span>
<span class="hljs-keyword">const</span> value = {
user, setUser,
cart, setCart,
theme, setTheme,
notifications, setNotifications,
products, setProducts,
orders, setOrders,
<span class="hljs-comment">// ... and all the rest</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">AppContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">AppContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// This component only needs theme, but re-renders when user, cart, etc. change</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeToggle</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { theme, setTheme } = useContext(AppContext); <span class="hljs-comment">// Gets ALL context data</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ThemeToggle rendering'</span>); <span class="hljs-comment">// This logs way too often!</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span></span>
);
}
Why this is bad:
-
Components re-render when unrelated state changes
-
Poor performance as your app grows
-
Hard to debug which state changes cause which re-renders
-
Difficult to optimize individual pieces of state
Solution: Separate contexts by domain
<span class="hljs-comment">// ✅ BETTER: Separate contexts for different domains</span>
<span class="hljs-keyword">const</span> UserContext = createContext();
<span class="hljs-keyword">const</span> CartContext = createContext();
<span class="hljs-keyword">const</span> ThemeContext = createContext();
<span class="hljs-keyword">const</span> NotificationContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState(<span class="hljs-literal">null</span>);
<span class="hljs-keyword">const</span> [isAuthenticated, setIsAuthenticated] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-comment">// Only user-related state here</span>
<span class="hljs-keyword">const</span> value = useMemo(<span class="hljs-function">() =></span> ({
user,
setUser,
isAuthenticated,
setIsAuthenticated
}), [user, isAuthenticated]);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">UserContext.Provider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [theme, setTheme] = useState(<span class="hljs-string">'light'</span>);
<span class="hljs-keyword">const</span> [fontSize, setFontSize] = useState(<span class="hljs-string">'medium'</span>);
<span class="hljs-comment">// Only theme-related state here</span>
<span class="hljs-keyword">const</span> value = useMemo(<span class="hljs-function">() =></span> ({
theme,
setTheme,
fontSize,
setFontSize
}), [theme, fontSize]);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ThemeContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">ThemeContext.Provider</span>></span></span>
);
}
<span class="hljs-comment">// Now ThemeToggle only re-renders when theme changes</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ThemeToggle</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { theme, setTheme } = useContext(ThemeContext); <span class="hljs-comment">// Only theme data</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'ThemeToggle rendering'</span>); <span class="hljs-comment">// Only logs when theme changes</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setTheme(theme === 'light' ? 'dark' : 'light')}>
Theme: {theme}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span></span>
);
}
Pitfall 3: Not memoizing context values
The Problem:
<span class="hljs-comment">// ❌ WRONG: Creates new objects every render</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [items, setItems] = useState([]);
<span class="hljs-keyword">const</span> [total, setTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{</span>
// <span class="hljs-attr">This</span> <span class="hljs-attr">creates</span> <span class="hljs-attr">a</span> <span class="hljs-attr">NEW</span> <span class="hljs-attr">object</span> <span class="hljs-attr">every</span> <span class="hljs-attr">time</span> <span class="hljs-attr">CartProvider</span> <span class="hljs-attr">renders</span>!
<span class="hljs-attr">items</span>, // <span class="hljs-attr">Same</span> <span class="hljs-attr">data</span> <span class="hljs-attr">but</span> <span class="hljs-attr">new</span> <span class="hljs-attr">object</span> <span class="hljs-attr">reference</span>
<span class="hljs-attr">total</span>, // <span class="hljs-attr">Same</span> <span class="hljs-attr">data</span> <span class="hljs-attr">but</span> <span class="hljs-attr">new</span> <span class="hljs-attr">object</span> <span class="hljs-attr">reference</span>
<span class="hljs-attr">addItem:</span> (<span class="hljs-attr">item</span>) =></span> { // NEW function every render!
setItems([...items, item]);
},
removeItem: (id) => { // NEW function every render!
setItems(items.filter(item => item.id !== id));
}
}}>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
Why this is bad:
-
React uses
Object.is()
to compare context values -
Even if data is the same, new objects cause all consumers to re-render
-
New functions break optimization in child components
-
Performance degrades as more components use the context
Solution: Memoize context values and functions
<span class="hljs-comment">// ✅ CORRECT: Memoize the context value and functions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [items, setItems] = useState([]);
<span class="hljs-keyword">const</span> [total, setTotal] = useState(<span class="hljs-number">0</span>);
<span class="hljs-comment">// useCallback memoizes functions - they only change when dependencies change</span>
<span class="hljs-keyword">const</span> addItem = useCallback(<span class="hljs-function">(<span class="hljs-params">item</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prevItems</span> =></span> [...prevItems, item]); <span class="hljs-comment">// Use function update to avoid dependency</span>
}, []); <span class="hljs-comment">// Empty deps = function never changes</span>
<span class="hljs-keyword">const</span> removeItem = useCallback(<span class="hljs-function">(<span class="hljs-params">id</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prevItems</span> =></span> prevItems.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== id));
}, []);
<span class="hljs-keyword">const</span> updateQuantity = useCallback(<span class="hljs-function">(<span class="hljs-params">id, quantity</span>) =></span> {
setItems(<span class="hljs-function"><span class="hljs-params">prevItems</span> =></span>
prevItems.map(<span class="hljs-function"><span class="hljs-params">item</span> =></span>
item.id === id ? { ...item, quantity } : item
)
);
}, []);
<span class="hljs-comment">// useMemo memoizes the context value object</span>
<span class="hljs-keyword">const</span> value = useMemo(<span class="hljs-function">() =></span> ({
items,
total,
addItem,
removeItem,
updateQuantity,
<span class="hljs-attr">itemCount</span>: items.length <span class="hljs-comment">// Computed value</span>
}), [items, total, addItem, removeItem, updateQuantity]);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">CartContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">CartContext.Provider</span>></span></span>
);
}
What useCallback and useMemo do:
-
useCallback(fn, deps) returns the same function reference until dependencies change
-
useMemo(fn, deps) returns the same value until dependencies change
-
Why this matters: React components only re-render when their props change by reference
Pitfall 4: Prop drilling when Context would be better
The Problem:
<span class="hljs-comment">// ❌ WRONG: Passing user data through many components that don't use it</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'admin'</span> });
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Header</span> <span class="hljs-attr">user</span>=<span class="hljs-string">{user}</span> /></span> {/* Header doesn't use user, just passes it down */}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params">{ user }</span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">header</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Logo</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">Navigation</span> <span class="hljs-attr">user</span>=<span class="hljs-string">{user}</span> /></span> {/* Navigation doesn't use user either */}
<span class="hljs-tag"></<span class="hljs-name">header</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navigation</span>(<span class="hljs-params">{ user }</span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">nav</span>></span>
<span class="hljs-tag"><<span class="hljs-name">MenuItem</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>></span>Home<span class="hljs-tag"></<span class="hljs-name">MenuItem</span>></span>
<span class="hljs-tag"><<span class="hljs-name">MenuItem</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/products"</span>></span>Products<span class="hljs-tag"></<span class="hljs-name">MenuItem</span>></span>
<span class="hljs-tag"><<span class="hljs-name">UserMenu</span> <span class="hljs-attr">user</span>=<span class="hljs-string">{user}</span> /></span> {/* Finally! Someone who uses user */}
<span class="hljs-tag"></<span class="hljs-name">nav</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserMenu</span>(<span class="hljs-params">{ user }</span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"user-menu"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>Welcome, {user.name}!<span class="hljs-tag"></<span class="hljs-name">span</span>></span> {/* This is where user is actually used */}
{user.role === 'admin' && <span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/admin"</span>></span>Admin Panel<span class="hljs-tag"></<span class="hljs-name">a</span>></span>}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Why this is problematic:
-
Header and Navigation don’t care about user but must know about it
-
Adding new user data requires updating multiple components
-
Components become tightly coupled
-
Testing becomes complex because you need to mock props that components don’t use
Solution: Use Context for data that skips intermediate components
<span class="hljs-comment">// ✅ BETTER: Use Context for data that needs to skip levels</span>
<span class="hljs-keyword">const</span> UserContext = createContext();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
<span class="hljs-keyword">const</span> [user, setUser] = useState({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'admin'</span> });
<span class="hljs-keyword">const</span> value = useMemo(<span class="hljs-function">() =></span> ({ user, setUser }), [user]);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>></span>
{children}
<span class="hljs-tag"></<span class="hljs-name">UserContext.Provider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useUser</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> context = useContext(UserContext);
<span class="hljs-keyword">if</span> (!context) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'useUser must be used within UserProvider'</span>);
}
<span class="hljs-keyword">return</span> context;
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">UserProvider</span>></span>
<span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Header</span> /></span> {/* No props needed! */}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
<span class="hljs-tag"></<span class="hljs-name">UserProvider</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">header</span>></span>
<span class="hljs-tag"><<span class="hljs-name">Logo</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">Navigation</span> /></span> {/* No props needed! */}
<span class="hljs-tag"></<span class="hljs-name">header</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Navigation</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">nav</span>></span>
<span class="hljs-tag"><<span class="hljs-name">MenuItem</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/"</span>></span>Home<span class="hljs-tag"></<span class="hljs-name">MenuItem</span>></span>
<span class="hljs-tag"><<span class="hljs-name">MenuItem</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/products"</span>></span>Products<span class="hljs-tag"></<span class="hljs-name">MenuItem</span>></span>
<span class="hljs-tag"><<span class="hljs-name">UserMenu</span> /></span> {/* No props needed! */}
<span class="hljs-tag"></<span class="hljs-name">nav</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserMenu</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { user } = useUser(); <span class="hljs-comment">// Gets user data directly from context</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"user-menu"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>Welcome, {user.name}!<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
{user.role === 'admin' && <span class="hljs-tag"><<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/admin"</span>></span>Admin Panel<span class="hljs-tag"></<span class="hljs-name">a</span>></span>}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
Pitfall 5: Using global state for everything
The Problem:
<span class="hljs-comment">// ❌ WRONG: Putting local UI state in global store</span>
<span class="hljs-keyword">const</span> useAppStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-comment">// Global state (good)</span>
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">cart</span>: { <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> },
<span class="hljs-attr">theme</span>: <span class="hljs-string">'light'</span>,
<span class="hljs-comment">// Local UI state (bad - should be local to component)</span>
<span class="hljs-attr">loginModalOpen</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">searchQuery</span>: <span class="hljs-string">''</span>,
<span class="hljs-attr">currentPage</span>: <span class="hljs-number">1</span>,
<span class="hljs-attr">sortDirection</span>: <span class="hljs-string">'asc'</span>,
<span class="hljs-attr">selectedFilters</span>: [],
<span class="hljs-comment">// Actions for everything</span>
<span class="hljs-attr">setLoginModalOpen</span>: <span class="hljs-function">(<span class="hljs-params">open</span>) =></span> set({ <span class="hljs-attr">loginModalOpen</span>: open }),
<span class="hljs-attr">setSearchQuery</span>: <span class="hljs-function">(<span class="hljs-params">query</span>) =></span> set({ <span class="hljs-attr">searchQuery</span>: query }),
<span class="hljs-attr">setCurrentPage</span>: <span class="hljs-function">(<span class="hljs-params">page</span>) =></span> set({ <span class="hljs-attr">currentPage</span>: page }),
<span class="hljs-comment">// ... many more actions</span>
}));
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SearchBox</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { searchQuery, setSearchQuery } = useAppStore();
<span class="hljs-comment">// This causes ALL components using the store to re-render when user types!</span>
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">input</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">{searchQuery}</span>
<span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setSearchQuery(e.target.value)}
/></span>
);
}
Why this is bad:
-
Every keystroke causes all store consumers to re-render
-
Store becomes cluttered with temporary UI state
-
Hard to reset state when component unmounts
-
Increases coupling between unrelated components
Solution: Keep local state local, global state global
<span class="hljs-comment">// ✅ BETTER: Separate local and global concerns</span>
<span class="hljs-keyword">const</span> useAppStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-comment">// Only truly global state</span>
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">cart</span>: { <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> },
<span class="hljs-attr">theme</span>: <span class="hljs-string">'light'</span>,
<span class="hljs-comment">// Actions for global state only</span>
<span class="hljs-attr">setUser</span>: <span class="hljs-function">(<span class="hljs-params">user</span>) =></span> set({ user }),
<span class="hljs-attr">addToCart</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">cart</span>: {
<span class="hljs-attr">items</span>: [...state.cart.items, product],
<span class="hljs-attr">total</span>: state.cart.total + product.price
}
})),
<span class="hljs-attr">setTheme</span>: <span class="hljs-function">(<span class="hljs-params">theme</span>) =></span> set({ theme })
}));
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SearchBox</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Local state for local concerns</span>
<span class="hljs-keyword">const</span> [searchQuery, setSearchQuery] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> [isSearching, setIsSearching] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-keyword">const</span> handleSearch = <span class="hljs-keyword">async</span> () => {
setIsSearching(<span class="hljs-literal">true</span>);
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> results = <span class="hljs-keyword">await</span> searchAPI(searchQuery);
<span class="hljs-comment">// Handle results...</span>
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-comment">// Handle error...</span>
} <span class="hljs-keyword">finally</span> {
setIsSearching(<span class="hljs-literal">false</span>);
}
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
<span class="hljs-tag"><<span class="hljs-name">input</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">{searchQuery}</span>
<span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setSearchQuery(e.target.value)} // No global re-renders!
/>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleSearch}</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{isSearching}</span>></span>
{isSearching ? 'Searching...' : 'Search'}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LoginModal</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-comment">// Modal open/closed state is local to this component</span>
<span class="hljs-keyword">const</span> [isOpen, setIsOpen] = useState(<span class="hljs-literal">false</span>);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> setIsOpen(true)}>Login<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
{isOpen && (
<span class="hljs-tag"><<span class="hljs-name">Modal</span> <span class="hljs-attr">onClose</span>=<span class="hljs-string">{()</span> =></span> setIsOpen(false)}>
<span class="hljs-tag"><<span class="hljs-name">LoginForm</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">Modal</span>></span>
)}
<span class="hljs-tag"></></span></span>
);
}
Guidelines for what belongs where:
-
Local state: Form inputs, modal open/closed, loading states, temporary UI state
-
Global state: User authentication, shopping cart, theme, data shared across pages
Pitfall 6: Not handling loading and error states in shared state
The Problem:
<span class="hljs-comment">// ❌ WRONG: Not handling async operations properly</span>
<span class="hljs-keyword">const</span> useUserStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
<span class="hljs-comment">// Missing loading and error states!</span>
<span class="hljs-attr">login</span>: <span class="hljs-keyword">async</span> (email, password) => {
<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> authAPI.login(email, password); <span class="hljs-comment">// What if this fails?</span>
set({ user });
}
}));
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LoginForm</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { login } = useUserStore();
<span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (e) => {
e.preventDefault();
<span class="hljs-keyword">await</span> login(email, password); <span class="hljs-comment">// No way to show loading or handle errors</span>
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>></span>
<span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setEmail(e.target.value)} />
<span class="hljs-tag"><<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setPassword(e.target.value)} />
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>></span>Login<span class="hljs-tag"></<span class="hljs-name">button</span>></span> {/* No loading state */}
<span class="hljs-tag"></<span class="hljs-name">form</span>></span></span>
);
}
Solution: Always include loading and error states
<span class="hljs-comment">// ✅ BETTER: Handle async operations properly</span>
<span class="hljs-keyword">const</span> useUserStore = create(<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">login</span>: <span class="hljs-keyword">async</span> (email, password) => {
set({ <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> }); <span class="hljs-comment">// Start loading, clear previous errors</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> authAPI.login(email, password);
set({ user, <span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> }); <span class="hljs-comment">// Success</span>
} <span class="hljs-keyword">catch</span> (error) {
set({
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: error.message || <span class="hljs-string">'Login failed'</span>, <span class="hljs-comment">// Store error message</span>
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>
});
}
},
<span class="hljs-attr">logout</span>: <span class="hljs-function">() =></span> {
set({ <span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>, <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> }); <span class="hljs-comment">// Clear user and any errors</span>
},
<span class="hljs-attr">clearError</span>: <span class="hljs-function">() =></span> {
set({ <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> }); <span class="hljs-comment">// Allow manual error clearing</span>
}
}));
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">LoginForm</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { login, loading, error, clearError } = useUserStore();
<span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-keyword">async</span> (e) => {
e.preventDefault();
clearError(); <span class="hljs-comment">// Clear any previous errors</span>
<span class="hljs-keyword">await</span> login(email, password);
};
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>></span>
{error && (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"error-message"</span>></span>
{error}
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{clearError}</span>></span>×<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
)}
<span class="hljs-tag"><<span class="hljs-name">input</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span>
<span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setEmail(e.target.value)}
disabled={loading} // Disable during loading
/>
<span class="hljs-tag"><<span class="hljs-name">input</span>
<span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span>
<span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =></span> setPassword(e.target.value)}
disabled={loading} // Disable during loading
/>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{loading}</span>></span>
{loading ? 'Logging in...' : 'Login'} {/* Show loading state */}
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">form</span>></span></span>
);
}
Best Practices for Maintainable Shared State
Following established patterns makes your code easier to understand and maintain.
1. Use consistent naming conventions
Be descriptive and consistent with your naming:
<span class="hljs-comment">// ✅ GOOD: Clear, descriptive names</span>
<span class="hljs-keyword">const</span> useCartStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-comment">// State names are clear</span>
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">totalPrice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">isLoading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>,
<span class="hljs-comment">// Action names describe what they do</span>
<span class="hljs-attr">addItemToCart</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">items</span>: [...state.items, { ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">totalPrice</span>: state.totalPrice + product.price,
<span class="hljs-attr">itemCount</span>: state.itemCount + <span class="hljs-number">1</span>
})),
<span class="hljs-attr">removeItemFromCart</span>: <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> {
<span class="hljs-keyword">const</span> itemToRemove = state.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (!itemToRemove) <span class="hljs-keyword">return</span> state;
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: state.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId),
<span class="hljs-attr">totalPrice</span>: state.totalPrice - (itemToRemove.price * itemToRemove.quantity),
<span class="hljs-attr">itemCount</span>: state.itemCount - itemToRemove.quantity
};
}),
<span class="hljs-attr">clearCart</span>: <span class="hljs-function">() =></span> set({
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">totalPrice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">itemCount</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>
})
}));
<span class="hljs-comment">// ❌ BAD: Unclear, inconsistent names</span>
<span class="hljs-keyword">const</span> useStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-comment">// Unclear what these are</span>
<span class="hljs-attr">data</span>: [],
<span class="hljs-attr">num</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">count</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">err</span>: <span class="hljs-literal">null</span>,
<span class="hljs-comment">// Unclear what these do</span>
<span class="hljs-attr">add</span>: <span class="hljs-function">(<span class="hljs-params">x</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">s</span>) =></span> ({ <span class="hljs-attr">data</span>: [...s.data, x] })),
<span class="hljs-attr">remove</span>: <span class="hljs-function">(<span class="hljs-params">id</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">s</span>) =></span> ({ <span class="hljs-attr">data</span>: s.data.filter(<span class="hljs-function"><span class="hljs-params">i</span> =></span> i.id !== id) })),
<span class="hljs-attr">clear</span>: <span class="hljs-function">() =></span> set({ <span class="hljs-attr">data</span>: [], <span class="hljs-attr">num</span>: <span class="hljs-number">0</span> })
}));
2. Group related state and actions together
Organize your state by feature, not by type:
<span class="hljs-comment">// ✅ GOOD: Organized by feature domains</span>
<span class="hljs-keyword">const</span> useAppStore = create(<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-comment">// User-related state</span>
<span class="hljs-attr">user</span>: {
<span class="hljs-attr">profile</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">preferences</span>: {},
<span class="hljs-attr">isAuthenticated</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>
},
<span class="hljs-comment">// Cart-related state</span>
<span class="hljs-attr">cart</span>: {
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">total</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">discount</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>
},
<span class="hljs-comment">// UI-related state</span>
<span class="hljs-attr">ui</span>: {
<span class="hljs-attr">theme</span>: <span class="hljs-string">'light'</span>,
<span class="hljs-attr">sidebarOpen</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">currentPage</span>: <span class="hljs-string">'home'</span>,
<span class="hljs-attr">notifications</span>: []
},
<span class="hljs-comment">// User actions</span>
<span class="hljs-attr">userActions</span>: {
<span class="hljs-attr">login</span>: <span class="hljs-keyword">async</span> (credentials) => {
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">user</span>: { ...state.user, <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> }
}));
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> profile = <span class="hljs-keyword">await</span> authAPI.login(credentials);
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">user</span>: {
...state.user,
profile,
<span class="hljs-attr">isAuthenticated</span>: <span class="hljs-literal">true</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>
}
}));
} <span class="hljs-keyword">catch</span> (error) {
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">user</span>: {
...state.user,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: error.message
}
}));
}
},
<span class="hljs-attr">logout</span>: <span class="hljs-function">() =></span> {
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">user</span>: {
<span class="hljs-attr">profile</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">preferences</span>: {},
<span class="hljs-attr">isAuthenticated</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>
}
}));
}
},
<span class="hljs-comment">// Cart actions</span>
<span class="hljs-attr">cartActions</span>: {
<span class="hljs-attr">addItem</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">cart</span>: {
...state.cart,
<span class="hljs-attr">items</span>: [...state.cart.items, { ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }],
<span class="hljs-attr">total</span>: state.cart.total + product.price
}
})),
<span class="hljs-attr">removeItem</span>: <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
<span class="hljs-keyword">const</span> state = get();
<span class="hljs-keyword">const</span> item = state.cart.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (item) {
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">cart</span>: {
...state.cart,
<span class="hljs-attr">items</span>: state.cart.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId),
<span class="hljs-attr">total</span>: state.cart.total - (item.price * item.quantity)
}
}));
}
}
},
<span class="hljs-comment">// UI actions</span>
<span class="hljs-attr">uiActions</span>: {
<span class="hljs-attr">setTheme</span>: <span class="hljs-function">(<span class="hljs-params">theme</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">ui</span>: { ...state.ui, theme }
})),
<span class="hljs-attr">toggleSidebar</span>: <span class="hljs-function">() =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">ui</span>: { ...state.ui, <span class="hljs-attr">sidebarOpen</span>: !state.ui.sidebarOpen }
})),
<span class="hljs-attr">addNotification</span>: <span class="hljs-function">(<span class="hljs-params">notification</span>) =></span> set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">ui</span>: {
...state.ui,
<span class="hljs-attr">notifications</span>: [...state.ui.notifications, {
<span class="hljs-attr">id</span>: <span class="hljs-built_in">Date</span>.now(),
...notification
}]
}
}))
}
}));
<span class="hljs-comment">// Usage is clean and organized</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProductCard</span>(<span class="hljs-params">{ product }</span>) </span>{
<span class="hljs-keyword">const</span> addItem = useAppStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.cartActions.addItem);
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"product-card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>{product.name}<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> addItem(product)}>
Add to Cart
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
3. Create selector hooks for complex data access
Make data access predictable and reusable:
<span class="hljs-comment">// ✅ GOOD: Dedicated selector hooks</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCartSelectors</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> items = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.items);
<span class="hljs-keyword">const</span> totalPrice = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.totalPrice);
<span class="hljs-keyword">const</span> itemCount = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.itemCount);
<span class="hljs-keyword">const</span> isLoading = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.isLoading);
<span class="hljs-keyword">const</span> error = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.error);
<span class="hljs-comment">// Computed values</span>
<span class="hljs-keyword">const</span> isEmpty = itemCount === <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> hasDiscount = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.discount > <span class="hljs-number">0</span>);
<span class="hljs-keyword">const</span> finalTotal = totalPrice - useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.discount);
<span class="hljs-keyword">return</span> {
items,
totalPrice,
itemCount,
isLoading,
error,
isEmpty,
hasDiscount,
finalTotal
};
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCartActions</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> addItem = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.addItemToCart);
<span class="hljs-keyword">const</span> removeItem = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.removeItemFromCart);
<span class="hljs-keyword">const</span> updateQuantity = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.updateItemQuantity);
<span class="hljs-keyword">const</span> clearCart = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.clearCart);
<span class="hljs-keyword">const</span> applyDiscount = useCartStore(<span class="hljs-function"><span class="hljs-params">state</span> =></span> state.applyDiscount);
<span class="hljs-keyword">return</span> {
addItem,
removeItem,
updateQuantity,
clearCart,
applyDiscount
};
}
<span class="hljs-comment">// Clean component usage</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartSummary</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { items, finalTotal, isEmpty, isLoading } = useCartSelectors();
<span class="hljs-keyword">const</span> { removeItem, clearCart } = useCartActions();
<span class="hljs-keyword">if</span> (isLoading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>Loading cart...<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
<span class="hljs-keyword">if</span> (isEmpty) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>Your cart is empty<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-summary"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>Cart Summary<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Total: ${finalTotal.toFixed(2)}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
{items.map(item => (
<span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{item.id}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"cart-item"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">span</span>></span>{item.name} x {item.quantity}<span class="hljs-tag"></<span class="hljs-name">span</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> removeItem(item.id)}>Remove<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span>
))}
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{clearCart}</span>></span>Clear Cart<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
4. Handle side effects properly
Separate side effects from state updates:
<span class="hljs-comment">// ✅ GOOD: Proper side effect handling</span>
<span class="hljs-keyword">const</span> useCartStore = create(<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-attr">items</span>: [],
<span class="hljs-attr">totalPrice</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">addItem</span>: <span class="hljs-function">(<span class="hljs-params">product</span>) =></span> {
<span class="hljs-comment">// Update state</span>
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> {
<span class="hljs-keyword">const</span> newItems = [...state.items, { ...product, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }];
<span class="hljs-keyword">const</span> newTotal = state.totalPrice + product.price;
<span class="hljs-keyword">return</span> {
<span class="hljs-attr">items</span>: newItems,
<span class="hljs-attr">totalPrice</span>: newTotal
};
});
<span class="hljs-comment">// Handle side effects AFTER state update</span>
<span class="hljs-keyword">const</span> newState = get();
<span class="hljs-comment">// Analytics tracking</span>
analytics.track(<span class="hljs-string">'Item Added to Cart'</span>, {
<span class="hljs-attr">productId</span>: product.id,
<span class="hljs-attr">productName</span>: product.name,
<span class="hljs-attr">cartTotal</span>: newState.totalPrice,
<span class="hljs-attr">itemCount</span>: newState.items.length
});
<span class="hljs-comment">// Save to localStorage</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'cart'</span>, <span class="hljs-built_in">JSON</span>.stringify({
<span class="hljs-attr">items</span>: newState.items,
<span class="hljs-attr">totalPrice</span>: newState.totalPrice
}));
<span class="hljs-comment">// Show notification</span>
toast.success(<span class="hljs-string">`<span class="hljs-subst">${product.name}</span> added to cart!`</span>);
<span class="hljs-comment">// Update browser tab title</span>
<span class="hljs-built_in">document</span>.title = <span class="hljs-string">`Shopping (<span class="hljs-subst">${newState.items.length}</span>) - MyStore`</span>;
},
<span class="hljs-attr">removeItem</span>: <span class="hljs-function">(<span class="hljs-params">productId</span>) =></span> {
<span class="hljs-keyword">const</span> currentState = get();
<span class="hljs-keyword">const</span> itemToRemove = currentState.items.find(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id === productId);
<span class="hljs-keyword">if</span> (!itemToRemove) <span class="hljs-keyword">return</span>;
<span class="hljs-comment">// Update state</span>
set(<span class="hljs-function">(<span class="hljs-params">state</span>) =></span> ({
<span class="hljs-attr">items</span>: state.items.filter(<span class="hljs-function"><span class="hljs-params">item</span> =></span> item.id !== productId),
<span class="hljs-attr">totalPrice</span>: state.totalPrice - (itemToRemove.price * itemToRemove.quantity)
}));
<span class="hljs-comment">// Side effects</span>
<span class="hljs-keyword">const</span> newState = get();
analytics.track(<span class="hljs-string">'Item Removed from Cart'</span>, {
<span class="hljs-attr">productId</span>: itemToRemove.id,
<span class="hljs-attr">productName</span>: itemToRemove.name,
<span class="hljs-attr">cartTotal</span>: newState.totalPrice
});
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'cart'</span>, <span class="hljs-built_in">JSON</span>.stringify({
<span class="hljs-attr">items</span>: newState.items,
<span class="hljs-attr">totalPrice</span>: newState.totalPrice
}));
toast.info(<span class="hljs-string">`<span class="hljs-subst">${itemToRemove.name}</span> removed from cart`</span>);
<span class="hljs-built_in">document</span>.title = <span class="hljs-string">`Shopping (<span class="hljs-subst">${newState.items.length}</span>) - MyStore`</span>;
}
}));
5. Implement proper error boundaries
Handle errors gracefully at the state level:
<span class="hljs-comment">// ✅ GOOD: Comprehensive error handling</span>
<span class="hljs-keyword">const</span> useApiStore = create(<span class="hljs-function">(<span class="hljs-params">set, get</span>) =></span> ({
<span class="hljs-attr">data</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">retryCount</span>: <span class="hljs-number">0</span>,
<span class="hljs-attr">fetchData</span>: <span class="hljs-keyword">async</span> (url, options = {}) => {
<span class="hljs-keyword">const</span> { maxRetries = <span class="hljs-number">3</span>, retryDelay = <span class="hljs-number">1000</span> } = options;
set({ <span class="hljs-attr">loading</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> });
<span class="hljs-keyword">const</span> attemptFetch = <span class="hljs-keyword">async</span> (attempt) => {
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
<span class="hljs-keyword">if</span> (!response.ok) {
<span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP <span class="hljs-subst">${response.status}</span>: <span class="hljs-subst">${response.statusText}</span>`</span>);
}
<span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
set({
data,
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">retryCount</span>: <span class="hljs-number">0</span>
});
} <span class="hljs-keyword">catch</span> (error) {
<span class="hljs-built_in">console</span>.error(<span class="hljs-string">`Fetch attempt <span class="hljs-subst">${attempt}</span> failed:`</span>, error);
<span class="hljs-keyword">if</span> (attempt < maxRetries) {
<span class="hljs-comment">// Retry with exponential backoff</span>
<span class="hljs-keyword">const</span> delay = retryDelay * <span class="hljs-built_in">Math</span>.pow(<span class="hljs-number">2</span>, attempt - <span class="hljs-number">1</span>);
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> attemptFetch(attempt + <span class="hljs-number">1</span>), delay);
set({ <span class="hljs-attr">retryCount</span>: attempt });
} <span class="hljs-keyword">else</span> {
<span class="hljs-comment">// Final failure</span>
set({
<span class="hljs-attr">loading</span>: <span class="hljs-literal">false</span>,
<span class="hljs-attr">error</span>: {
<span class="hljs-attr">message</span>: error.message,
<span class="hljs-attr">type</span>: <span class="hljs-string">'FETCH_ERROR'</span>,
<span class="hljs-attr">timestamp</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toISOString(),
url,
<span class="hljs-attr">attempts</span>: attempt
},
<span class="hljs-attr">retryCount</span>: <span class="hljs-number">0</span>
});
}
}
};
<span class="hljs-keyword">await</span> attemptFetch(<span class="hljs-number">1</span>);
},
<span class="hljs-attr">retry</span>: <span class="hljs-function">() =></span> {
<span class="hljs-keyword">const</span> state = get();
<span class="hljs-keyword">if</span> (state.error && state.error.url) {
state.fetchData(state.error.url);
}
},
<span class="hljs-attr">clearError</span>: <span class="hljs-function">() =></span> {
set({ <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> });
}
}));
<span class="hljs-comment">// Error boundary component</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiErrorBoundary</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
<span class="hljs-keyword">constructor</span>(props) {
<span class="hljs-built_in">super</span>(props);
<span class="hljs-built_in">this</span>.state = { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">error</span>: <span class="hljs-literal">null</span> };
}
<span class="hljs-keyword">static</span> getDerivedStateFromError(error) {
<span class="hljs-keyword">return</span> { <span class="hljs-attr">hasError</span>: <span class="hljs-literal">true</span>, error };
}
componentDidCatch(error, errorInfo) {
<span class="hljs-built_in">console</span>.error(<span class="hljs-string">'API Error Boundary caught an error:'</span>, error, errorInfo);
<span class="hljs-comment">// Report to error tracking service</span>
errorTracking.report(error, {
<span class="hljs-attr">componentStack</span>: errorInfo.componentStack,
<span class="hljs-attr">context</span>: <span class="hljs-string">'ApiErrorBoundary'</span>
});
}
render() {
<span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.state.hasError) {
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"error-fallback"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h2</span>></span>Something went wrong<span class="hljs-tag"></<span class="hljs-name">h2</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>We're sorry, but something unexpected happened.<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =></span> this.setState({ hasError: false, error: null })}>
Try Again
<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.props.children;
}
}
<span class="hljs-comment">// Usage with error handling</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DataDisplay</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> { data, loading, error, retry } = useApiStore();
useEffect(<span class="hljs-function">() =></span> {
useApiStore.getState().fetchData(<span class="hljs-string">'/api/data'</span>);
}, []);
<span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>Loading...<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>;
<span class="hljs-keyword">if</span> (error) {
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"error-state"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">h3</span>></span>Failed to load data<span class="hljs-tag"></<span class="hljs-name">h3</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>{error.message}<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">p</span>></span>Attempted {error.attempts} times<span class="hljs-tag"></<span class="hljs-name">p</span>></span>
<span class="hljs-tag"><<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{retry}</span>></span>Retry<span class="hljs-tag"></<span class="hljs-name">button</span>></span>
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">div</span>></span>
{data && <span class="hljs-tag"><<span class="hljs-name">pre</span>></span>{JSON.stringify(data, null, 2)}<span class="hljs-tag"></<span class="hljs-name">pre</span>></span>}
<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>
);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">return</span> (
<span class="xml"><span class="hljs-tag"><<span class="hljs-name">ApiErrorBoundary</span>></span>
<span class="hljs-tag"><<span class="hljs-name">DataDisplay</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">ApiErrorBoundary</span>></span></span>
);
}
Conclusion: Building Maintainable React Applications
Managing shared state complexity is one of the most important skills to have for building scalable React applications. The key is choosing the right tool for each situation and following established patterns.
Summary of approaches
Start simple and scale up:
-
Local state for component-specific data
-
Context for moderate shared state that doesn’t change frequently
-
State management libraries for complex, frequently-changing global state
-
Custom hooks for reusable stateful logic
Key principles to remember
1. Principle of least power: Use the simplest solution that meets your needs
-
Don’t use Redux for a theme toggle
-
Don’t use local state for user authentication
-
Don’t use Context for rapidly changing data
2. Separation of concerns: Keep related state together, unrelated state apart
-
Group user state separately from cart state
-
Don’t mix temporary UI state with persistent data
-
Separate actions from selectors
3. Performance matters: Optimize for your specific use case
-
Memoize context values to prevent unnecessary re-renders
-
Use selective subscriptions in state management libraries
-
Split large contexts into smaller, focused ones
4. Maintainability first: Write code that future developers (including yourself) can understand
-
Use descriptive names for state and actions
-
Handle loading and error states consistently
-
Write comprehensive tests for your state logic
The evolution of a typical application
Most successful React applications follow this pattern:
Phase 1: Simple local state
<span class="hljs-comment">// Start here for new features</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ContactForm</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
<span class="hljs-comment">// Simple and focused</span>
}
Phase 2: Context for shared data
<span class="hljs-comment">// Move to Context when multiple components need the same data</span>
<span class="hljs-keyword">const</span> UserContext = createContext();
<span class="hljs-comment">// Used by Header, Sidebar, UserProfile components</span>
Phase 3: State management library for complex interactions
<span class="hljs-comment">// Scale to Redux/Zustand when state becomes complex</span>
<span class="hljs-keyword">const</span> useAppStore = create(<span class="hljs-function">(<span class="hljs-params">set</span>) =></span> ({
<span class="hljs-attr">user</span>: <span class="hljs-literal">null</span>,
<span class="hljs-attr">cart</span>: { <span class="hljs-attr">items</span>: [], <span class="hljs-attr">total</span>: <span class="hljs-number">0</span> },
<span class="hljs-attr">orders</span>: [],
<span class="hljs-comment">// Many interconnected pieces of state</span>
}));
Phase 4: Custom hooks for reusable patterns
<span class="hljs-comment">// Extract reusable logic into custom hooks</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useApi</span>(<span class="hljs-params">url</span>) </span>{
<span class="hljs-comment">// Reusable API logic with loading, error, and retry</span>
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useLocalStorage</span>(<span class="hljs-params">key, defaultValue</span>) </span>{
<span class="hljs-comment">// Reusable localStorage sync</span>
}
Final recommendations
For beginners: Start with local state and Context. Master these before moving to state management libraries.
For intermediate developers: Learn one state management library well (Zustand or Redux Toolkit). Focus on proper error handling and performance optimization.
For advanced developers: Experiment with different patterns and create reusable abstractions. Focus on team consistency and maintainable architectures.
For teams: Establish conventions early and document your state management patterns. Code reviews should focus on proper state placement and performance implications.
The goal is not to eliminate all complexity, but to manage it in a way that scales with your application and team. Every piece of shared state should have a clear owner, predictable update patterns, and proper error handling.
Remember: the best state management solution is often a combination of approaches. A well-architected React application uses local state for local concerns, Context for moderate sharing, state management libraries for complex global state, and custom hooks for reusable logic.
By following these principles and patterns, you’ll build React applications that are not only functional but also maintainable, performant, and enjoyable to work with as they grow in complexity.
Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & MoreÂ