State Management (Redux, Context API)
Manage global app state. Differentiate Context API for small state and Redux, actions, reducers, and stores for large apps.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is state management and why is it important?
State management is handling application state centrally. It prevents prop drilling, makes debugging easier, and enables scaling.
// Without management - prop drilling
<App user={user} setUser={setUser}>
<Header user={user} setUser={setUser}>
<Nav user={user} />
</Header>
</App>
// With management
<Provider>
<App />
</Provider>
Q2. What is Redux and how does it work?
// Redux: Predictable state container
// 1. Action - describes what happened
const INCREMENT = 'INCREMENT';
const action = { type: INCREMENT, payload: 1 };
// 2. Reducer - takes state and action, returns new state
function counterReducer(state = 0, action) {
switch(action.type) {
case INCREMENT:
return state + action.payload;
default:
return state;
}
}
// 3. Store - holds application state
import { createStore } from 'redux';
const store = createStore(counterReducer);
// 4. Dispatch - send action
store.dispatch({ type: INCREMENT, payload: 1 });
// 5. Subscribe - listen to changes
store.subscribe(() => {
console.log(store.getState());
});
Q3. What are the alternatives to Redux?
Context API, Recoil, Zustand, MobX, etc.
Q4. How do you use Redux Thunk for async actions?
// Redux Thunk - middleware for async operations
function fetchUser(userId) {
return dispatch => {
dispatch({ type: 'FETCH_USER_REQUEST' });
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
})
.catch(error => {
dispatch({ type: 'FETCH_USER_ERROR', payload: error });
});
};
}
// Using
store.dispatch(fetchUser(1));
Q5. What is Redux Saga?
// Redux Saga - side effects management
import { call, put, takeEvery } from 'redux-saga/effects';
function* fetchUserSaga(action) {
try {
const user = yield call(fetchUser, action.payload);
yield put({ type: 'FETCH_USER_SUCCESS', payload: user });
} catch (error) {
yield put({ type: 'FETCH_USER_ERROR', payload: error });
}
}
function* rootSaga() {
yield takeEvery('FETCH_USER_REQUEST', fetchUserSaga);
}
Q6. What is Recoil and why use it over Redux?
// Recoil - simpler state management
import { atom, selector, useRecoilState } from 'recoil';
// Atom - unit of state
const userAtom = atom({
key: 'user',
default: null
});
// Component
function UserComponent() {
const [user, setUser] = useRecoilState(userAtom);
return <div>{user?.name}</div>;
}
// Selector - derived state
const userEmailSelector = selector({
key: 'userEmail',
get: ({ get }) => {
const user = get(userAtom);
return user?.email;
}
});
Q7. How do you handle global state without Redux?
// Using Context API with useReducer
const StoreContext = React.createContext();
function StoreProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={{ state, dispatch }}>
{children}
</StoreContext.Provider>
);
}
// Custom hook
function useStore() {
return useContext(StoreContext);
}
// Usage
function Component() {
const { state, dispatch } = useStore();
}
Q8. What is MobX?
// MobX - reactive state management
import { makeObservable, observable, action } from 'mobx';
import { observer } from 'mobx-react';
class Store {
count = 0;
constructor() {
makeObservable(this, {
count: observable,
increment: action
});
}
increment() {
this.count++;
}
}
const store = new Store();
const Counter = observer(() => (
<button onClick={() => store.increment()}>
{store.count}
</button>
));
Q9. How do you handle authentication state?
// Authentication context
const AuthContext = createContext();
function AuthProvider({ children }) {
const [auth, setAuth] = useState(null);
const login = async (email, password) => {
const response = await fetch('/api/login', {
method: 'POST',
body: JSON.stringify({ email, password })
});
const data = await response.json();
setAuth(data);
localStorage.setItem('token', data.token);
};
const logout = () => {
setAuth(null);
localStorage.removeItem('token');
};
return (
<AuthContext.Provider value={{ auth, login, logout }}>
{children}
</AuthContext.Provider>
);
}
Q10. What is Zustand?
// Zustand - minimal state management
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}</button>
);
}
State Management (Redux, Context API)
Manage global app state. Differentiate Context API for small state and Redux, actions, reducers, and stores for large apps.
What is state management and why is it important?
State management is handling application state centrally. It prevents prop drilling, makes debugging easier, a...
What is Redux and how does it work?
// Redux: Predictable state container // 1. Action - describes what happened const INCREMENT = 'INCREMENT'; co...
What are the alternatives to Redux?
Context API, Recoil, Zustand, MobX, etc.
How do you use Redux Thunk for async actions?
// Redux Thunk - middleware for async operations function fetchUser(userId) { return dispatch => { dispa...
What is Redux Saga?
// Redux Saga - side effects management import { call, put, takeEvery } from 'redux-saga/effects'; function*...
What is Recoil and why use it over Redux?
// Recoil - simpler state management import { atom, selector, useRecoilState } from 'recoil'; // Atom - unit...
How do you handle global state without Redux?
// Using Context API with useReducer const StoreContext = React.createContext(); function StoreProvider({ chi...
What is MobX?
// MobX - reactive state management import { makeObservable, observable, action } from 'mobx'; import { observ...
How do you handle authentication state?
// Authentication context const AuthContext = createContext(); function AuthProvider({ children }) { const...
What is Zustand?
// Zustand - minimal state management import create from 'zustand'; const useStore = create((set) => ({ cou...