Appearance
State Management
39. What is prop drilling, and how do you avoid it?
The short answer
Prop drilling is passing a prop through several layers of components that do not use it, only so a deeply nested child can receive it. It makes components harder to change, because every layer in between must know about and forward the prop. Avoid it by composing differently, passing elements as children so the middle layers never see the data, by using Context for widely needed, rarely changing values, or by using a store such as Zustand or Redux for shared application state.
tsx
// Drilling: Page and Sidebar only forward `user`
function Page({ user }: { user: User }) { return <Sidebar user={user} /> }
function Sidebar({ user }: { user: User }) { return <AccountMenu user={user} /> }
function AccountMenu({ user }: { user: User }) { return <span>{user.name}</span> }Three ways out, from simplest:
tsx
// 1. Composition: the top component builds the deep child and passes it as a slot
function Page({ user }: { user: User }) {
return <Sidebar menu={<AccountMenu user={user} />} /> // Sidebar never sees user
}
function Sidebar({ menu }: { menu: React.ReactNode }) { return <aside>{menu}</aside> }
// 2. Context: for values many components need
const UserContext = createContext<User | null>(null)
function AccountMenu2() { const user = useContext(UserContext); return <span>{user?.name}</span> }
// 3. A store: for shared state that changes often
const useSession = create<{ user: User | null }>()(() => ({ user: null }))
function AccountMenu3() { const name = useSession((s) => s.user?.name); return <span>{name}</span> }Do not over-correct. Passing a prop down two levels is normal and clear. Reach for context or a store when the drilling is deep, frequent, or the data is truly global.
40. When should you use Context versus a state library?
The short answer
Context is a way to pass a value down the tree, not a state manager; it re-renders every consumer whenever the value changes. Use it for values that change rarely and are needed widely: theme, locale, the signed-in user, feature flags. Use a state library, such as Zustand or Redux Toolkit, for shared state that changes often or is read by many components, because components subscribe to just the slice they need. For data from the server, use TanStack Query instead of either.
| Need | Best fit |
|---|---|
| Theme, locale, current user, injected services | Context |
| UI state shared across distant components: cart drawer open, filters, wizard steps | Zustand, or Redux Toolkit |
| Large app, many developers, strict patterns, time-travel debugging | Redux Toolkit |
| Data that lives on a server: products, orders, profile | TanStack Query or RTK Query (question 46) |
| State used by one component or a small subtree | useState, useReducer |
Why Context struggles with fast-changing state:
tsx
const CartContext = createContext<{ items: Item[]; count: number; total: number } | null>(null)Every component reading CartContext re-renders whenever anything in it changes, even a component that only shows count. A store with selectors avoids that:
tsx
const count = useCart((s) => s.items.length) // re-renders only when the count changesA healthy default for new apps: local state first, TanStack Query for server data, a small Zustand store for the few truly shared UI values, and Context for dependency-like values. Reach for Redux Toolkit when the team or the state is large enough to benefit from its structure.
41. What is Redux, and how does its data flow work?
The short answer
Redux is a library that keeps application state in one central store, a plain JavaScript object. The UI never changes it directly. Instead, it dispatches actions, plain objects that describe what happened, such as { type: 'cart/itemAdded', payload: 'tea' }. Pure functions called reducers take the current state and the action and return the new state. Components read state through selectors and re-render when the slice they selected changes. The flow is always one direction, which makes changes predictable and easy to trace.
The three rules of Redux:
| Rule | Meaning |
|---|---|
| One source of truth | All shared state lives in one store |
| State is read-only | The only way to change it is to dispatch an action |
| Changes are pure functions | Reducers compute the new state without side effects |
Why teams adopted it: every change is an action you can log, inspect and replay with Redux DevTools; the logic for how state changes is in one place; and the strict pattern scales to large teams. Its old reputation for boilerplate came from hand-written action types and switch statements, which Redux Toolkit removed (question 42).
42. What does Redux Toolkit add, and what is createSlice?
The short answer
Redux Toolkit, RTK, is the official, recommended way to write Redux. configureStore sets up the store with good defaults, DevTools and middleware in one call. createSlice generates action creators and a reducer from one object of "case reducers", and lets you write updates that look like mutations, state.items.push(item), because the Immer library turns them into safe immutable updates. It also includes createAsyncThunk for async logic and RTK Query for data fetching.
ts
// cartSlice.ts
import { createSlice, type PayloadAction } from '@reduxjs/toolkit'
type CartItem = { sku: string; qty: number }
type CartState = { items: CartItem[]; coupon: string | null }
const initialState: CartState = { items: [], coupon: null }
const cartSlice = createSlice({
name: 'cart', // (1)
initialState,
reducers: {
itemAdded(state, action: PayloadAction<string>) { // (2)
const line = state.items.find((i) => i.sku === action.payload)
if (line) line.qty += 1 // (3)
else state.items.push({ sku: action.payload, qty: 1 })
},
itemRemoved(state, action: PayloadAction<string>) {
state.items = state.items.filter((i) => i.sku !== action.payload)
},
couponApplied(state, action: PayloadAction<string>) {
state.coupon = action.payload
},
},
})
export const { itemAdded, itemRemoved, couponApplied } = cartSlice.actions // (4)
export default cartSlice.reducerts
// store.ts
import { configureStore } from '@reduxjs/toolkit'
import { useDispatch, useSelector } from 'react-redux'
import cart from './cartSlice'
export const store = configureStore({ reducer: { cart } }) // (5)
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
export const useAppSelector = useSelector.withTypes<RootState>() // (6)
export const useAppDispatch = useDispatch.withTypes<AppDispatch>()tsx
// CartButton.tsx
function CartButton({ sku }: { sku: string }) {
const dispatch = useAppDispatch()
const count = useAppSelector((s) => s.cart.items.reduce((n, i) => n + i.qty, 0)) // (7)
return <button onClick={() => dispatch(itemAdded(sku))}>Add ({count})</button>
}- The slice name prefixes action types, such as
cart/itemAdded. - A case reducer, typed with the shape of its payload.
- "Mutating" code is safe here. Immer records the changes on a draft and produces a new, unchanged-elsewhere state object. Outside
createSliceorcreateReducer, never mutate state. - Action creators are generated for you.
configureStorewires the reducers, the thunk middleware and DevTools, and adds development checks that warn about accidental mutation.- Typed hooks, so every component gets
RootStatewithout repeating the type. - A selector that picks only what this button needs. The component re-renders only when the count changes.
What RTK replaced: hand-written action type constants, action creator functions, switch statements and spreading nested objects by hand.
43. What are thunks and middleware in Redux?
The short answer
Reducers must be pure, so async work such as calling an API cannot live in them. Middleware sits between dispatching an action and the reducer, and can intercept, delay or add actions; logging, analytics and async handling are middleware. A thunk is the most common async middleware pattern: you dispatch a function instead of an object, the function runs, awaits the API call, and dispatches normal actions with the results. createAsyncThunk generates the pending, fulfilled and rejected actions for you.
ts
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
export const placeOrder = createAsyncThunk(
'orders/place', // (1)
async (cartId: string, { rejectWithValue }) => {
const res = await fetch('/api/orders', { method: 'POST', body: JSON.stringify({ cartId }) })
if (!res.ok) return rejectWithValue(await res.json()) // (2)
return (await res.json()) as { orderId: string }
},
)
const ordersSlice = createSlice({
name: 'orders',
initialState: { status: 'idle' as 'idle' | 'placing' | 'placed' | 'failed', lastOrderId: null as string | null },
reducers: {},
extraReducers: (builder) => {
builder
.addCase(placeOrder.pending, (s) => { s.status = 'placing' }) // (3)
.addCase(placeOrder.fulfilled, (s, a) => { s.status = 'placed'; s.lastOrderId = a.payload.orderId })
.addCase(placeOrder.rejected, (s) => { s.status = 'failed' })
},
})
// in a component
await dispatch(placeOrder(cartId)).unwrap() // (4)- The type prefix for the three generated actions:
orders/place/pending,/fulfilledand/rejected. - Return a structured error for the rejected case.
- Reducers respond to the lifecycle to set loading and result state.
unwrap()gives the component a normal promise that throws on rejection, for showing a message or navigating.
Other middleware options: the listener middleware, built into RTK, runs side effects in response to actions, such as "when an order is placed, clear the cart and send analytics". Older codebases may use redux-saga, built on generators, or redux-observable, built on RxJS. For plain data fetching, RTK Query is usually better than writing thunks (question 44).
44. What is RTK Query?
The short answer
RTK Query is the data fetching and caching tool built into Redux Toolkit. You define an API once, with endpoints for queries and mutations, and it generates React hooks such as useGetOrdersQuery, which handle loading and error states, caching, de-duplication, refetching and cache invalidation through tags. It solves the same problem as TanStack Query, but stores its cache inside the Redux store, which suits teams already using Redux.
ts
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const shopApi = createApi({
reducerPath: 'shopApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api', credentials: 'include' }),
tagTypes: ['Order'], // (1)
endpoints: (build) => ({
getOrders: build.query<Order[], void>({
query: () => '/orders',
providesTags: ['Order'], // (2)
}),
cancelOrder: build.mutation<void, string>({
query: (id) => ({ url: `/orders/${id}/cancel`, method: 'POST' }),
invalidatesTags: ['Order'], // (3)
}),
}),
})
export const { useGetOrdersQuery, useCancelOrderMutation } = shopApi // (4)
// store: configureStore({ reducer: { [shopApi.reducerPath]: shopApi.reducer }, middleware: (g) => g().concat(shopApi.middleware) })
function OrderList() {
const { data: orders = [], isLoading } = useGetOrdersQuery()
const [cancelOrder] = useCancelOrderMutation()
if (isLoading) return <Spinner />
return orders.map((o) => <button key={o.id} onClick={() => cancelOrder(o.id)}>Cancel {o.id}</button>)
}- Tags name kinds of cached data.
- This query provides
Orderdata. - Cancelling invalidates it, so every component showing orders refetches automatically.
- Hooks are generated from the endpoint names.
| RTK Query | TanStack Query | |
|---|---|---|
| Cache lives | In the Redux store | In its own QueryClient |
| API defined | Centrally, with createApi | At each useQuery, or in custom hooks |
| Invalidation | Tags | Query keys (question 50) |
| Best when | The app already uses Redux | Any app; the more popular choice |
45. What is Zustand, and how does it compare with Redux?
The short answer
Zustand is a small state library where a store is a hook: you create it with a function that returns state and the functions that change it, and components read just the parts they need with a selector. There are no providers, actions or reducers to write, so it has very little boilerplate. It suits most shared client state. Redux Toolkit adds structure, conventions, middleware and DevTools time travel, which help large teams with complex state, at the cost of more code.
ts
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type CartStore = {
items: { sku: string; qty: number }[]
add: (sku: string) => void
remove: (sku: string) => void
clear: () => void
}
export const useCart = create<CartStore>()(
persist( // (1)
(set) => ({
items: [],
add: (sku) => set((s) => { // (2)
const line = s.items.find((i) => i.sku === sku)
return {
items: line
? s.items.map((i) => (i.sku === sku ? { ...i, qty: i.qty + 1 } : i))
: [...s.items, { sku, qty: 1 }],
}
}),
remove: (sku) => set((s) => ({ items: s.items.filter((i) => i.sku !== sku) })),
clear: () => set({ items: [] }),
}),
{ name: 'cart' }, // (3)
),
)
function CartBadge() {
const count = useCart((s) => s.items.reduce((n, i) => n + i.qty, 0)) // (4)
return <span>{count}</span>
}
function AddButton({ sku }: { sku: string }) {
const add = useCart((s) => s.add) // (5)
return <button onClick={() => add(sku)}>Add</button>
}- Optional middleware:
persistsaves the cart tolocalStorageand restores it on load. setmerges a partial update into the state. Return new arrays and objects; do not mutate.- The storage key.
- A selector: the badge re-renders only when the count changes.
- Selecting only the function: functions never change, so this button never re-renders because of the cart.
A selector trap: returning a new object from a selector, useCart((s) => ({ items: s.items, add: s.add })), creates a new object each time, which re-renders on every store change, or loops. Select values separately, or wrap the selector with useShallow.
| Zustand | Redux Toolkit | |
|---|---|---|
| Setup | One create call, no provider | Store, slices, provider |
| Updates | Call functions on the store | Dispatch actions to reducers |
| Boilerplate | Very little | Moderate |
| DevTools | Via middleware | Built in, with time travel |
| Conventions | Few; you decide | Strong, consistent across teams |
| Good for | Most apps' shared UI state | Large apps, many developers, complex flows |
46. What is the difference between server state and client state?
The short answer
Client state belongs only to the browser: whether a drawer is open, the current tab, a draft in a form. Your app owns it and it is always up to date. Server state is a copy of data that lives on a server, such as products, orders or the user's profile: someone else can change it, your copy can become out of date, and you must fetch, cache, refresh and invalidate it. Treating server state like client state, by copying API results into Redux or Context by hand, is the source of most data bugs in React apps, which is why data libraries exist.
| Client state | Server state | |
|---|---|---|
| Owned by | Your app | The server |
| Can be changed by others | No | Yes: other users, other tabs, jobs |
| Can go stale | No | Yes |
| Needs | Simple storage | Fetching, caching, refreshing, de-duplication, retries |
| Tools | useState, Zustand, Redux | TanStack Query, RTK Query, framework loaders |
| Examples | Modal open, theme, wizard step | Products, cart on the server, orders, notifications |
The bug-prone old pattern:
tsx
useEffect(() => {
fetch('/api/orders').then((r) => r.json()).then((orders) => dispatch(ordersLoaded(orders)))
}, [])You now hand-write loading flags, error handling, refetching after mutations, invalidation when another screen changes an order, and you have to remember not to fetch the same thing twice from two components.
The split that works:
tsx
const { data: orders } = useQuery({ queryKey: ['orders'], queryFn: fetchOrders }) // server state
const isFilterOpen = useUi((s) => s.isFilterOpen) // client stateEach tool does what it is good at, and the Redux or Zustand store becomes much smaller (question 47).