React Interview Questions - State Management (61-90)
Master React state management for FAANG interviews: local state, Context API, Redux, Zustand, Jotai, Recoil, and more with practical examples.
Master React state management for FAANG interviews: local state, Context API, Redux, Zustand, Jotai, Recoil, and more with practical examples. This interview-focused guide covers essential react interview questions - state management (61-90) concepts for technical interviews.
React Interview Questions - State Management (61-90)
Managing state is one of the most critical parts of React applications, especially as they scale.
Question 61: What is state management in React?
State management is the process of handling data that changes in a React application. This includes local component state, global application state, and data fetching.
Question 62: Local vs Global State
| Local State | Global State |
|---|---|
| Used in one or a few components | Shared across many components |
| Stored in useState, useReducer | Stored in Context, Redux, Zustand, etc. |
| Simpler | More complex but scalable |
Question 63: What is Redux?
Redux is a predictable state container for JavaScript apps. It helps manage global state in a single store.
Core Principles:
- Single source of truth: State is stored in a single store
- State is read-only: Only way to change state is to dispatch an action
- Changes are made with pure functions: Reducers are pure functions
Question 64: Explain Redux Flow
The Redux flow is:
- User does something → Dispatch an Action
- Action is sent to Reducer
- Reducer updates Store
- Components re-render with new state
Question 65: What is an action in Redux?
Actions are plain JavaScript objects that describe what happened. They have a type field.
Example:
const addTodoAction = {
type: 'todos/addTodo',
payload: { id: 1, text: 'Learn Redux' }
};
Question 66: What is a reducer in Redux?
Reducers are pure functions that take the current state and an action and return a new state.
Example:
const initialState = { todos: [] };
function todoReducer(state = initialState, action) {
switch (action.type) {
case 'todos/addTodo':
return {
...state,
todos: [...state.todos, action.payload]
};
case 'todos/deleteTodo':
return {
...state,
todos: state.todos.filter(todo => todo.id !== action.payload)
};
default:
return state;
}
}
Question 67: What is a Redux store?
The store is where the app's state lives. You can:
getState(): Read statedispatch(action): Update statesubscribe(listener): Listen for changes
Example:
import { createStore } from 'redux';
const store = createStore(todoReducer);
Question 68: What is Redux Toolkit (RTK)?
Redux Toolkit is the official, recommended approach to writing Redux. It simplifies Redux with utilities like configureStore, createSlice, and createAsyncThunk.
Question 69: Redux Toolkit Example
Here's a simple todo app with RTK:
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { useSelector, useDispatch } from 'react-redux';
// Slice
const todosSlice = createSlice({
name: 'todos',
initialState: { todos: [] },
reducers: {
addTodo: (state, action) => {
// RTK lets us write "mutating" code - it uses Immer under the hood!
state.todos.push(action.payload);
},
deleteTodo: (state, action) => {
state.todos = state.todos.filter(todo => todo.id !== action.payload);
}
}
});
export const { addTodo, deleteTodo } = todosSlice.actions;
// Store
export const store = configureStore({
reducer: {
todos: todosSlice.reducer
}
});
// Usage in component
function TodoList() {
const todos = useSelector(state => state.todos.todos);
const dispatch = useDispatch();
return (
<div>
{todos.map(todo => (
<li key={todo.id}>
{todo.text}
<button onClick={() => dispatch(deleteTodo(todo.id))}>Delete</button>
</li>
))}
</div>
);
}
Question 70: What is Immer in Redux Toolkit?
Immer is a library that lets you write "mutating" code that gets converted into immutable updates. It makes reducers easier to write!
Question 71: What are selectors?
Selectors are functions that extract and return specific parts of the state. They can be memoized for performance.
Example (with Reselect):
import { createSelector } from '@reduxjs/toolkit';
const selectTodos = state => state.todos.todos;
export const selectDoneTodos = createSelector(
[selectTodos],
(todos) => todos.filter(todo => todo.done)
);
Question 72: What is Context API for state management?
Context API is built into React and lets you share state globally without prop drilling. It's great for:
- Theme
- Authentication
- Language
Question 73: Context API vs Redux
| Context API | Redux |
|---|---|
| Built into React | External library |
| Simple for small-to-medium apps | Better for large, complex apps |
| No devtools (unless you use React DevTools) | Great devtools (time travel debugging!) |
| No middleware | Supports middleware (thunks, sagas) |
Question 74: What is Zustand?
Zustand is a lightweight, fast state management library that's simpler than Redux but still powerful.
Example:
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
decrement: () => set(state => ({ count: state.count - 1 })),
}));
// Usage
function Counter() {
const count = useStore(state => state.count);
const increment = useStore(state => state.increment);
return <button onClick={increment}>Count: {count}</button>;
}
Question 75: What is Jotai?
Jotai is a primitive and flexible state management library that uses atoms (small pieces of state) instead of a single store.
Example:
import { atom, useAtom } from 'jotai';
const countAtom = atom(0);
function Counter() {
const [count, setCount] = useAtom(countAtom);
return <button onClick={() => setCount(c => c + 1)}>Count: {count}</button>;
}
Question 76: What is Recoil?
Recoil is a state management library from Meta that uses atoms and selectors. It integrates well with React and is good for complex apps.
Question 77: What is MobX?
MobX uses observable state - components re-render when data they use changes. It's more "magical" and less boilerplate-heavy.
Question 78: When to use Context API vs Zustand vs Redux
| Use Case | Library |
|---|---|
| App is small, state only shared in a few places | Context API |
| App is medium-sized, want something simple | Zustand |
| App is large, complex, needs middleware/devtools | Redux Toolkit |
Question 79: How to manage form state?
Options:
- Local state (controlled components)
- React Hook Form
- Formik
Question 80: React Hook Form Example
import { useForm } from 'react-hook-form';
function LoginForm() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => {
console.log(data); // { email: "...", password: "..." }
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
{...register('email', { required: true, pattern: /^\S+@\S+$/i })}
placeholder="Email"
/>
{errors.email && <span>Email is required!</span>}
<input
{...register('password', { required: true })}
type="password"
placeholder="Password"
/>
{errors.password && <span>Password is required!</span>}
<button type="submit">Login</button>
</form>
);
}
Question 81: What is Formik?
Formik is a popular form library that helps with form state, validation, and submission.
Question 82: What is middleware in Redux?
Middleware sits between dispatch and reducers. Common uses:
- Async operations (Thunks, Sagas)
- Logging
- Crash reporting
Question 83: What is Redux Thunk?
Redux Thunk is middleware that lets you write async logic that interacts with the store.
Example:
const fetchUserById = (userId) => {
return async (dispatch) => {
dispatch({ type: 'users/fetchUser/pending' });
try {
const res = await fetch(`/api/users/${userId}`);
const data = await res.json();
dispatch({ type: 'users/fetchUser/fulfilled', payload: data });
} catch (e) {
dispatch({ type: 'users/fetchUser/rejected', payload: e.message });
}
};
};
Question 84: What is createAsyncThunk in RTK?
createAsyncThunk simplifies creating async thunks in Redux Toolkit.
Example:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
const fetchUserById = createAsyncThunk(
'users/fetchUserById',
async (userId) => {
const res = await fetch(`/api/users/${userId}`);
return res.json();
}
);
const userSlice = createSlice({
name: 'users',
initialState: { data: null, status: 'idle' },
extraReducers: (builder) => {
builder
.addCase(fetchUserById.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchUserById.fulfilled, (state, action) => {
state.status = 'succeeded';
state.data = action.payload;
});
}
});
Question 85: What is Redux Saga?
Redux Saga is middleware that uses generator functions to handle side effects in Redux.
Question 86: What is RTK Query?
RTK Query is a powerful data fetching and caching tool built into Redux Toolkit.
Question 87: What is React Query (TanStack Query)?
React Query is a library for data fetching, caching, and synchronization. It simplifies managing server state.
Example:
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
function Todos() {
const { data: todos, isLoading, error } = useQuery({
queryKey: ['todos'],
queryFn: () => fetchTodos()
});
const queryClient = useQueryClient();
const addTodoMutation = useMutation({
mutationFn: addTodo,
onSuccess: () => {
// Invalidate todo cache
queryClient.invalidateQueries(['todos']);
}
});
if (isLoading) return 'Loading...';
return (
<div>
<ul>{todos.map(todo => <li key={todo.id}>{todo.text}</li>)}</ul>
<button onClick={() => addTodoMutation.mutate({ text: 'New Todo' })}>Add Todo</button>
</div>
);
}
Question 88: Local state composition
You can combine useReducer and useContext to create a Redux-like state management system without external libraries.
Question 89: What is server state vs client state?
| Server State | Client State |
|---|---|
| Stored on backend (database) | Stored in React app |
| Need to fetch from server | Managed locally |
| Should be cached | Usually doesn't need caching |
| Use React Query/SWR/Axios | Use useState/useReducer/Context/Redux |
Question 90: Best practices for state management
- Keep state as local as possible
- Use single source of truth
- Keep state normalized
- Use memoization for performance
- Use devtools to debug