Redux Flashcards

1
Q

What is Redux?

A

Redux is a pattern and library for managing and updating application state, using events called “actions”. It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion.

Redux helps you manage “global” state - state that is needed across many parts of your application.

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

What is the Redux Cycle

A

1) Action Creator
2) Action
3) dispatch
4) Reducer
5) State

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

What is an Action Creator?

A

One of the approaches is to write action objects directly in the code, where they’re being dispatched.

dispatch({ type: ‘todos/todoAdded’, payload: trimmedText })

However, a much better approach is to use action creator functions. An action creator is a function that creates and returns an action object. We typically use these so we don’t have to write the action object by hand every time:

const todoAdded = text => {
  return {
    type: 'todos/todoAdded',
    payload: text
  }
}

store.dispatch(todoAdded(‘Buy milk’))
Action creators have two primary purposes:

They prepare and format the contents of action objects
They encapsulate any additional work needed whenever we create those actions

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

What is a Redux store?

A

The center of every Redux application is the store. A “store” is a container that holds your application’s global state.

  • You must never directly modify or change the state that is kept inside the Redux store
  • The only way to cause an update to the state is to create a plain action object and then dispatch the action
  • When an action is dispatched, the store runs the root reducer function, and lets it calculate the new state based on the old state and the action
  • Finally, the store notifies subscribers that the state has been updated so the UI can be updated with the new data.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are Actions?

A

Actions are events that occur in the app based on user input and trigger updates in the state.

They are a plain JavaScript objects that have a type field. One can think of an action as an event that describes something that happened in the application. We usually write that type string like “domain/eventName”,

A typical action object might look like this:

const addTodoAction = {
  type: 'todos/todoAdded',
  payload: 'Buy milk'
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are Reducers?

A

Reducers are functions that take the current state and an action as arguments, and return a new state result. In other words, (state, action) => newState

A Redux app really only has one reducer function: the “root reducer” function. That one root reducer function is responsible for handling all of the actions that are dispatched, and calculating what the entire new state result should be every time.

// Use the initialState as a default value
export default function appReducer(state = initialState, action) {
  // The reducer normally looks at the action type field to decide what happens
  switch (action.type) {
    default:
  return state   } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What does dispatch function do?

A

Dispatch function passes an Action created through an Action Creator to the reducer, which then handles the update of the state.

Setting up redux store, limits us to only updating the state of the store with store.dispatch together with action creator that we would like to use.

We will not be able to modify the state of the store like store.state.accounting - 100;

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

What is combineReducers function?

A

combineReducers accepts an object where the key names will become the keys in your root state object, and the values are the slice reducer functions that know how to update those slices of the Redux state.

import { combineReducers } from ‘redux’

const rootReducer = combineReducers({
  // Define a top-level state field named `todos`, handled by `todosReducer`
  todos: todosReducer,
  filters: filtersReducer
// the key names you give to combineReducers decides what the key names of your state object will be!
})
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you create a Redux store?

A

A Redux app really only has one reducer function: the “root reducer” function that you will pass to createStore.

One way is to use combineReducers function to create a root Reducer.

Then, we need to pass this reducer when we create Redux store.

const store = Redux.createStore(rootReducer);

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

What are the components that you create with the help of react-redux?

A

Provider - The Provider component makes the Redux store available to any nested components that need to access the Redux store. most applications will render a Provider at the top level, with the entire app’s component tree inside of it.

Connect - We wrap the component, we would like to access the global state with. It communicates with the Provider

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

What is the folder structure for creating a redux app?

A
/src
  /actions - Contains files related to action creators
  /components
  /reducers - Files related to reducers
  index.js
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is useSelector hook?

A

useSelector is a custom hook that comes together with the react-redux library.
It accepts a single function, which we call a selector function. A selector is a function that takes the entire Redux store state as its argument, reads some value from the state, and returns that result.

useSelector automatically subscribes to the Redux store for us! That way, any time an action is dispatched, it will call its selector function again right away. If the value returned by the selector changes from the last time it ran, useSelector will force our component to re-render with the new data. All we have to do is call useSelector() once in our component, and it does the rest of the work for us.

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

What is the caveat that differs useSelector from mapStateToProps

A

useSelector diverges from mapStateToProps in one fairly big way: it uses strict object reference equality (===) to determine if components should re-render instead of shallow object comparison.

useSelector is returning a different object literal each time it’s called. When the store is updated, React Redux will run this selector, and since a new object was returned, always determine that the component needs to re-render. The simple rule to avoid this is to either call useSelector once for each value of your state that you need:

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

or, when returning an object containing several values from the store, explicitly tell useSelector to use a shallow equality comparison

import { shallowEqual, useSelector } from ‘react-redux’;

const { count, user } = useSelector(state => ({
count: state.counter.count,
user: state.user,
}), shallowEqual);

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

What is useDispatch hook?

A

The React-Redux useDispatch hook gives us the store’s dispatch method as its result.

It gives us access to dispatch function that allows us to update the global state variables.

const dispatch - useDisptach();

dispatch(addToto(todo));

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

What are Selectors?

A

Selectors are functions that know how to extract specific pieces of information from a store state value. As an application grows bigger, this can help avoid repeating logic as different parts of the app need to read the same data.

const selectCounterValue = state => state.value

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

What is redux-thunk?

A

Redux thunk is a middleware that helps us to deal with asynchronous action creators.

The word “thunk” is a programming term that means “a piece of code that does some delayed work”. For Redux specifically, “thunks” are a pattern of writing functions with logic inside that can interact with a Redux store’s dispatch and getState methods.

What redux thunks essentially allows us to do, is to return a function instead of just a plain object from an action creator.

This function having completed, has access to getState and dispatch methods, and will run another dispatch, this time returning an object.

17
Q

How do we add redux thunk into our project?

A

We need to add it into our store

const store = createStore(reducers, applyMiddleware(thunk));

Then, redux thunk will handle all action creators, that are functions - meaning, deal with asynchronous code.

Example of an asynchronous action creator:

export const fetchPosts = () => async (dispatch) => {
  const response = await api.getPosts();

dispatch({ type: “FETCH_POSTS”, payload: response });
};

18
Q

What are the rules of Reducers?

A
  • Must return any value besides undefined
  • Produces state or data to be used inside of your app using previous state and the action
  • Must not return reach ‘out of itself’ to decide what value to return (reducers are pure)
  • Must not mutate its input ‘state’ argument
19
Q

What are the rules of Action Creators?

A
  • Action Creators must return action objects
  • Actions must have a type property
  • Actions can optionally have a ‘payload’
20
Q

What are the two ways of extracting logic to get one single item from an Array from the global state?

A
First option is, that 
const mapStateToProps = (state, ownProps) => 

accepts ownProps attribute, which then can be referenced to find the selected item by id or any other property.

Another way is to use function composition and wrap the selectUser selector with a function that accepts userId as an argument.

const selectUser = (userId) => (state) =>
  state.users.find((user) => user.id === userId);
21
Q

How can you memoize the api call results in the global state?

A

We can make use of a _.memoize function that is accessible in the lodash library. This approach has one flaw - you are not able to refetch the data using the specific action creator. Another approach is to create a fetchUsersAndPosts function which will reduce the
no. of api calls.

const _fetchUser = _.memoize(async (id, dispatch) => {
    const user = await api.getUser(id);
dispatch({ type: "FETCH_USER", payload: user }); });

export const fetchUser = (id) => (dispatch) => _fetchUser(id, dispatch);