Redux Flashcards

1
Q

How do you get the current state in redux?

A
store.getState();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

You have three reducers(aReducer, bReducer, cReducer). How do you combine these and create finally a store?

A

In store.js import all the reducers and createStore and combineReducers like this:

import { createStore, combineReducers } from 'redux';
import { aReducer } from '../features/a/aSlice.js;

Then create a bundled reducers Object:

const reducers = {
    aSlice: aReducer,
    etc. ...

Than create the rootReducer

const rootReducer = combineReducers(reducers);

and from there create and export the store:

export const store = createStore(rootReducer);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which data do you need to pass as props after importing the redux store into your index.js?

A

The current state of the store and dispatch to the <App></App>:

<App 
      state={store.getState()}
      dispatch={store.dispatch}
    />
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Where do you import the store in redux?

A

In the entry point. The index.js:

import { store } from './app/store.js'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you get the current state of the store in redux?

A
store.getState()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you listen to changes of the state of the store in redux in your index.js?

A
store.subscribe(render);

render is the function that renders the whole app component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you dispatch an action in redux?

A

By calling dispatch() with the action and it’s passed values:

dispatch(action(propA, propB))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you import the configureStore from Redux Toolki?

A
import { configureStore } from '@reduxjs/toolkit'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you setup an store in redux toolkit?

A

To set up a store in Redux Toolkit, you primarily use the configureStore function, which simplifies the process compared to the traditional Redux setup.

export configureStore({
 reducer: {
   todos: todosReducer,
   filters: filtersReducer
 }
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is createSlice in Redux Toolkit?

A

createSlice is a function that simplifies creating Redux logic by combining reducer, actions, and initialState in one place.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the purpose of the name field in createSlice?

A
  • Organizes actions under a common namespace.
  • Prevents naming conflicts between slices.
  • Improves readability in debugging tools like Redux DevTools.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are reducers in createSlice?

A

reducers is an object where each key is an action, and its value is a reducer function that updates the state based on the action.

const counterSlice = createSlice({
  name: "counter",
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; }
  }
});

export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Write a sample createSlice configuration for a counter with actions to increment and decrement.

A
const counterSlice = createSlice({
  name: 'counter',
  initialState: { value: 0 },
  reducers: {
    increment: (state) => { state.value += 1; },
    decrement: (state) => { state.value -= 1; }
  }
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can you make actions generated by createSlice available?

A

You make actions available by exporting them from the slice file:

export const { increment, decrement } = counterSlice.actions;

This allows them to be imported and used in components:

import { increment } from './counterSlice';

Then, you can dispatch them when needed:

dispatch(increment());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

In Redux/toolkit createAsyncThunk() accepts two arguments. In order, they are?

A

createAsyncThunk‘s arguments are an action type string and an asynchronous thunk function.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a thunk in redux?

A

A function returned by another function

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Which two programming concepts does Redux Toolkit use internally for createAsyncThunk()?

A

Middleware and thunks

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the purpose of middleware in Redux?

A

Redux middleware extends the store’s abilities and lets you write asynchronous logic that can interact with the store. Middleware is added to the store either through createStore() or configureStore().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you register a slice in the store in redux toolkit?

A

You register a slice in the store by adding its reducer to configureStore under the reducer key.

const store = configureStore({
  reducer: {
    counter: counterSlice.reducer
  }
});

counterSlice is the Slice Object and .reducer is all the reducers in counterSlice.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does a Reducer do?

A

A reducer is a function that takes the current state, processes an action, and returns a new state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

How does a component dispatch an Action?

A

Using dispatch(action), for example:

dispatch(increment());
dispatch(add(5));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What happens after dispatching an Action?

A
  1. The action is sent to the store.
  2. The store forwards it to the appropriate reducer.
  3. The reducer processes it and returns a new state.
  4. The UI updates automatically.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How does a component read the current state from the store in toolkit?

A

const count = useSelector((state) => state.counter.count);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you define actions with Redux Toolkit?

A

Actions are automatically created within createSlice():

const counterSlice = createSlice({
  name: "counter",
  initialState: { count: 0 },
  reducers: {
    increment: (state) => { state.count += 1; },
    add: (state, action) => { state.count += action.payload; }
  }
});

You can import and use them like this:

import { increment, add } from "./counterSlice";
dispatch(increment());
dispatch(add(5));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Explain the concept of thunk in Redux. How does it help in handling side effects?

A

A thunk is a middleware that allows action creators to return functions instead of plain action objects. This is useful for handling asynchronous logic (e.g., API calls) before dispatching actions to the reducer. The function receives dispatch and getState as arguments, allowing controlled updates to the state.

const fetchData = () => (dispatch, getState) => {
  fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => dispatch({ type: "DATA_LOADED", payload: data }));
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What is the role of connect() from react-redux? How does it work?

A

The connect() function is a higher-order component (HOC) that connects a React component to the Redux store. It allows components to subscribe to Redux state and dispatch actions without directly accessing the store.

const mapStateToProps = (state) => ({ count: state.count });
const mapDispatchToProps = (dispatch) => ({ increment: () => dispatch({ type: "INCREMENT" }) });

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

How does the useSelector hook differ from connect() in accessing state in Redux?

A
  • useSelector is a React Hook that allows functional components to access Redux state directly.
  • connect() is a HOC used with class components (or functional components) to connect to Redux.
  • useSelector has a simpler syntax and allows components to subscribe to only the specific slices of state they need, improving performance.
const count = useSelector(state => state.count);
28
Q

Explain the concept of immutability in the context of Redux. Why is it important?

A

Immutability in Redux means that the state should never be modified directly; instead, new state objects are created whenever changes occur.

Why is it important?

  • Ensures predictability of state changes.
  • Enables time-travel debugging (Redux DevTools).
  • Helps React detect state changes for efficient rendering.
return { ...state, value: 10 };  // ✅ Always return a new object
29
Q

What are the differences between mapStateToProps and mapDispatchToProps?

A
  • mapStateToProps(state) → Maps Redux state to component props.
  • mapDispatchToProps(dispatch) → Maps dispatch functions (actions) to component props.
const mapStateToProps = (state) => ({ count: state.count });
const mapDispatchToProps = (dispatch) => ({ increment: () => dispatch({ type: "INCREMENT" }) });
30
Q

Discuss the role of combineReducers in Redux. When and why would you use it?

A

combineReducers is used to split state management across multiple reducers. It allows different parts of the state to be managed independently.

const rootReducer = combineReducers({
  user: userReducer,
  posts: postsReducer,
});

👉 Use it when your app has multiple state slices managed by separate reducers.

31
Q

What are Redux selectors and why are they useful in large applications?

A

Selectors are functions that extract specific pieces of state from the Redux store.

Why use them?
✔ Avoid code duplication
✔ Improve performance (with memoization using reselect)
✔ Make refactoring easier

const selectUser = (state) => state.user;
const selectUserName = createSelector(selectUser, (user) => user.name);
32
Q

What is the purpose of Redux DevTools extension, and how do you configure it?

A

Redux DevTools allows developers to track actions, inspect state changes, and time-travel debug.

Configuration:
~~~
import { composeWithDevTools } from “redux-devtools-extension”;
const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(thunk)));
~~~

33
Q

What are middleware functions in Redux? Can you give examples of commonly used middleware?

A

Middleware extends Redux by intercepting actions before they reach the reducer.

Common middleware:

  • redux-thunk (handles async actions)
  • redux-saga (alternative for complex async flows)
  • logger (logs actions)
34
Q

What is Redux and why is it used in React applications?

A

Redux is a **state management library* for JavaScript applications. It helps manage global state in a predictable way, making debugging and scaling easier.

35
Q

What are the differences between Redux and the Context API?

A
  • Redux → Better for complex state logic & debugging (Redux DevTools).
  • Context API → Best for lightweight, simple state sharing (e.g., theme or auth state).

🔹 Use Redux for large applications with complex state logic.
🔹 Use Context API for small-scale state sharing.

36
Q

What are the core principles of Redux?

A
  • Single source of truth → One store for the entire state.
  • State is read-only → Changes only happen via actions.
  • Changes are made with pure functions → Reducers update state immutably.
37
Q

Explain the basic components of Redux architecture.

A
  1. Store → Holds the state.
  2. Actions → Describe state changes.
  3. Reducers → Handle actions & return new state.
  4. Middleware → Intercepts actions (e.g., async logic).
38
Q

What is the purpose of actions and reducers in Redux?

A
  • Actions → Describe what should happen.
  • Reducers → Define how the state changes in response to actions.
39
Q

How does Redux manage the state of an application?

A

Redux maintains state in a single immutable object in the store, which is updated by dispatching actions handled by reducers.

40
Q

What is the Redux store?

A

The store is the central container for the application state.

const store = createStore(rootReducer, applyMiddleware(thunk));
41
Q

Why should we dispatch an action to update the state and not update the store directly?

A

Direct state mutations break Redux’s predictability, time-travel debugging, and performance optimizations. Actions ensure controlled state updates.

42
Q

How does Redux handle asynchronous operations?

A

Redux uses middleware like redux-thunk or redux-saga to manage async actions like API calls.

44
Q

What does .addCase() do in Redux Toolkit?

A

.addCase() is a method used in extraReducers to handle specific action types. It connects each action type (e.g., fetchProducts.pending, fetchProducts.fulfilled) with a function that updates the Redux state.

~~~
builder.addCase(fetchProducts.pending, (state) => {
state.loading = true;
});```

45
Q

When do we use extraReducers instead of reducers?

A

extraReducers is used when we have asynchronous actions such as those generated by createAsyncThunk.

  • reducers are used for synchronous actions (e.g., updating the state directly).
  • extraReducers are for handling actions related to async operations, like pending, fulfilled, and rejected states from a createAsyncThunk.
46
Q

Why do we need to export pizzaSlice.reducer from the pizzaSlice.js?

A

The reducer is needed by Redux to manage the store. It tells Redux how to update the state when an action is dispatched.

Example of using it in a store:

import { configureStore } from '@reduxjs/toolkit';
import pizzaReducer from './pizzaSlice';

const store = configureStore({
  reducer: {
    pizza: pizzaReducer,
  },
});
47
Q

Why do we need to export pizzaSlice.actions from the pizzaSlice.js?

A

pizzaSlice.actions contains action creators, which are functions that return action objects. These actions can then be dispatched to update the state.

Example of an action creator and dispatching it:

import { useDispatch } from 'react-redux';
import { pizza_order } from './pizzaSlice';

const Component = () => {
  const dispatch = useDispatch();

  return <button onClick={() => dispatch(pizza_order())}>Order Pizza 🍕</button>;
};
48
Q

Why do we export both pizzaSlice.reducer and pizzaSlice.actions?

A
  • pizzaSlice.reducer is needed for the Redux store to manage state.
  • pizzaSlice.actions is needed for components to dispatch actions and trigger state changes.
49
Q

What does the Provider component do in Redux Toolkit?

A

It makes the Redux store available to the entire app by wrapping the root component.

<Provider store = {store}>
    <App />
  </Provider>
50
Q

How do you set up Provider in a React-Redux app?

A
  1. Create the store with configureStore().
  2. Wrap the app inside <Provider store={store}> in index.js or main.js.
51
Q

What happens when clicking this button?

<button onClick={() => dispatch(pizza_order())}>Order Pizza</button>
A

1️⃣ Button click triggers onClick.
2️⃣ Arrow function calls dispatch(pizza_order()).
3️⃣ dispatch sends an action to Redux.
4️⃣ The reducer updates state based on “ORDER_PIZZA”.
5️⃣ React re-renders UI if needed.

52
Q

What is Redux Toolkit and how does it differ from plain Redux?

A

Redux Toolkit is an official, opinionated library that simplifies Redux development by providing preconfigured tools (like createSlice and configureStore) to reduce boilerplate and enforce best practices. Unlike plain Redux, it minimizes manual setup and error-prone patterns.

53
Q

Why is Redux Toolkit recommended as the standard way to write Redux logic?

A

It streamlines development by reducing boilerplate, enforces best practices, integrates tools like Immer for immutability, and offers utilities (e.g., createSlice, createAsyncThunk) that simplify asynchronous logic and store configuration.

54
Q

What does createSlice do, and how does it simplify Redux setup?

A

createSlice combines the declaration of action types, action creators, and reducers into one cohesive unit (a slice). It auto-generates action creators and action types based on provided reducer functions, dramatically reducing boilerplate.

55
Q

How does createAsyncThunk work, and when should you use it?

A

createAsyncThunk handles asynchronous operations by dispatching automatically generated pending, fulfilled, and rejected actions based on a promise’s lifecycle. Use it for API calls or async logic to manage loading and error states seamlessly.

56
Q

What is configureStore, and how does it differ from Redux’s createStore?

A

configureStore simplifies store creation by automatically adding middleware (like redux-thunk and development checks), integrating Redux DevTools, and reducing manual setup. In contrast, createStore in plain Redux requires manual configuration of middleware and enhancers.

57
Q

How does Redux Toolkit handle immutability in reducers?

A

It uses Immer under the hood so that you can write “mutating” code (e.g., state.value++) which is automatically converted into immutable updates, simplifying state management.

58
Q

What is Immer, and how is it used in Redux Toolkit?

A

Immer is a library that enables you to write code that “mutates” state while actually producing immutable updates. Redux Toolkit integrates Immer by default in createSlice reducers to simplify immutable update logic.

59
Q

How does Redux Toolkit reduce boilerplate compared to traditional Redux?

A

It consolidates action types, action creators, and reducers into a single slice; automates store configuration with default middleware; and provides utilities like createAsyncThunk that manage async states, significantly cutting down repetitive code.

60
Q

What is the builder syntax in extraReducers and why is it useful?

A

The builder syntax is a callback pattern in extraReducers that allows you to add cases for different actions (e.g., pending, fulfilled, rejected from createAsyncThunk) in a clear and maintainable way, avoiding the need for manual switch-case statements.

61
Q

How can you customize middleware in configureStore?

A

You can pass a middleware array to configureStore via its middleware option, using getDefaultMiddleware to start with the defaults and then chaining methods like .concat() to add custom middleware or removing defaults as needed.

62
Q

How does Redux Toolkit handle errors in async actions?

A

With createAsyncThunk, errors automatically trigger a rejected action. The error details are stored in action.error, allowing reducers to capture and update error states without additional error-handling code.

63
Q

What is the structure of a typical slice created with createSlice?

A

A typical slice includes:

  • name: A unique identifier for the slice
  • initialState: The default state for that slice
  • reducers: Synchronous reducer functions (which auto-generate actions)
  • extraReducers: Handlers for external actions (e.g., those from createAsyncThunk)
64
Q

How do you handle loading states in Redux Toolkit?

A

Loading states are commonly managed in extraReducers when using createAsyncThunk. Set a loading flag to true on the pending action, and then set it to false upon fulfilled or rejected actions to indicate whether data is being fetched.

65
Q

How do you test async actions created with createAsyncThunk?

A

By mocking API calls and dispatching the thunk in a test environment, you can verify that the correct sequence of actions (pending, fulfilled, or rejected) is dispatched and that the state updates as expected.

66
Q

What common middleware does Redux Toolkit include by default?

A

Redux Toolkit’s configureStore includes middleware like redux-thunk for async logic, a serializable state invariant middleware, and immutability checks in development mode, ensuring robust defaults.

67
Q

What is getDefaultMiddleware in configureStore, and how can it be customized?

A

getDefaultMiddleware returns an array of default middleware used by configureStore. It can be customized by chaining methods (e.g., .concat() to add middleware or .filter() to remove specific middleware) to tailor the middleware pipeline.