Redux

And connected React libraries (redux-thunk, react-redux).

8 flashcards · Programming Languages · by lakesare

  1. import { createStore } from Redux; const store = createStore(___?___);

    Our reducer.

  2. const store = createStore(ourReducer); Name 3 store methods.

    store.getState() store.dispatch({ type: 'INCREMENT' }) store.subscribe(() => {}) accepts callback that will be called every time state updates

  3. Write a naive Redux store implementation.

    const createStore = (reducer) => { let state; let listeners; const getState = () => state; const dispatch = (action) => { state = reducer(state, action); listeners.forEach((listener) => listener()); } const subscribe = (listener) => { listeners.push(listener); } dispatch({}); // populates the default state return { getState, dispatch, subscribe }; }

  4. Why use reselect?

    To, at the same time,: store the minimal state (avoid having both state.courses and state.filteredCourses) avoid calculating deriveFilteredCourses(courses) on every render

  5. Why use redux-thunk?

    to be able to use return(dispatch, getState) in the action Seriously, other reasons are not convincing.

  6. Rewrite to use redux-thunk: @connect( () => ({}), (dispatch) => ({ createUser: (user) => actions.createUser(dispatch, user) }) ) const createUser = (dispatch, user) => dispatch({ type: 'CREATE', user });

    Note a getState function being passed too, it's an advantage. @connect( () => ({}), (dispatch) => ({ createUser: (user) => dispatch(actions.createUser(user)) }) ) const createUser = (user) => (dispatch, getState) => dispatch({ type: 'CREATE', user })

  7. Redux is criticized for absence of encapsulation. Consider you have a dropdown component used throughout the app. How would you reuse its actions?

    1. Create a reducer for a dropdown: const dropdownReducer = (state, action) => ({}) 2. Use this reducer in other reducers: const barReducer = (barState = {toggled: false, dropdown: null}, action) => { switch (action.type) { default: return { ...barState, dropdown: dropdownReducer(barState.qux, action) // Reducer composition }; } };

  8. What's the appeal of normalizr?

    It takes array, and returns dictionary with { 5 (id): {myBooook} }. To describe a simple array of a singular entity type: const data = [ { id: '123', name: 'Jim' }, { id: '456', name: 'Jane' } ]; const userSchema = new schema.Entity('users'); const userListSchema = new schema.Array(userSchema); // or use shorthand syntax: const userListSchema = [ userSchema ]; const normalizedData = normalize(data, userListSchema); Output { entities: { users: { '123': { id: '123', name: 'Jim' }, '456': { id: '4…