Skip to content

Redux

  • Redux is usually used with React
  • can be used with other frameworks

Redux vs React Context

  • Dan Abramov: You might not need redux
  • Redux actually uses React Context behind the scenes
  • Redux should only store JSON serializable stuff
    • Context can store anything like functions and react components

What Redux limits you to do

  • application state as plain objects and arrays
  • changes in the system as plain objects.
  • the logic for handling changes as pure functions.

Extra features Redux has

  • Redux Dev Tools
  • time travel debugging

Immutability Helper

Redux Hooks

useSelector

import { useSelector } from "react-redux";
const user = useSelector((state) => state.user);

useDispatch

import { useDispatch } from 'react-redux';
const dispatch = useDispatch();

dispatch({
    type: "ACTION_TYPE",
    ...
});

Before Redux Hooks: connect

Higher Order Component that injects more props to the component

const mapStateToProps = state => ({
  prop_injected_into_component: state.path.in.redux,
});

const mapDispatchToProps = dispatch => ({
// also injected as a prop into the component
    addToast: () => dispatch({type: "ADD_TOAST"}),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(MyComponent);

Redux Style Guide

  • only have JSON serializable data in Redux
    • no sets in Redux
    • it won't show up in the Redux Dev Tools
  • reducers shouldn't have side effects
    • no API calls in reducers

redux-thunk

What is a thunk

wrap a function around an expression to delay when it gets called

const x = 1 + 3
const myThunk = () => 1 + 3;

lets you pass functions that dispatch into dispatch

import { Action } from "redux";
import { ThunkDispatch } from "redux-thunk";
import { RootStateOrAny } from "react-redux";

function myAction(props) {
    return (dispatch: Dispatch<AnyAction>, getState: () => RootStateOrAny) => {
        dispatch({
            type: "MY_ACTION",
        });
    };
}

function fn(dispatch: ThunkDispatch<RootStateOrAny, ExtraThunkArg, Action>) {
    dispatch(myAction(props));
}

Provider

import { Provider } from 'react-redux'

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

similar to React Context Provider

const ThemeContext = React.createContext('light');
<ThemeContext.Provider value="dark">
  <Toolbar />
</ThemeContext.Provider>

Last update: 2022-09-23