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

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().

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.

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.

21
Q

How does a component dispatch an Action?

A

Using dispatch(action), for example:

dispatch(increment());
dispatch(add(5));
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.
23
Q

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

A

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

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));
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 }));
};
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);
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.