Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cooperka/e498044146470c95d431fad4a69bfa5f to your computer and use it in GitHub Desktop.
Save cooperka/e498044146470c95d431fad4a69bfa5f to your computer and use it in GitHub Desktop.
Redux (vanilla) vs Redux (hooks-for-redux) comparison

Vanilla Redux

Learn more

// Action type.
const ADD_TODO = 'ADD_TODO';

// Action creator.
function addTodo(todo) {
  return { type: ADD_TODO, todo };
}

// Reducer state.
initialState = {
  todos: ['Buy coffee'],
};

// Reducer.
function todoReducer(state = initialState, action) {
  switch (action.type) {
    // Handle each possible type of action.
    case ADD_TODO:
      return {
        ...state,
        todos: todos.concat(action.todo),
      },

    default:
      return state;
  }
}

// Create a store from your reducer.
const todoStore = createStore(todoReducer);

// Invoke an action.
todoStore.dispatch(addTodo('Drink coffee'));

// Render a component.
const TodoSummary = (props) => {
  const { todos } = props;
  return (
    <div>{todos.length}</div>
  );
}

// Extract props for your component.
function mapStateToProps(todoStore, props) {
  return {
    todos: todoStore.todos,
  };
}

// Connect your component to the store.
const TodoSummaryConnected = connect(mapStateToProps)(TodoSummary);

// Render your app.
const App = () => (
  <Provider store={todoStore}>
    <TodoSummaryConnected />
  </Provider>
)

Hooks for Redux (H4R)

Learn more

initialState = {
  todos: ['Buy coffee'],
};

// Create a reducer hook + dispatchers. Params are useRedux(storeName, initialState, reducers).
const [useTodoList, { addTodo }] = useRedux(
  "todoList",
  initialState,
  {
    addTodo: (todos, todo) => todos.concat(todo),
  }
);

// Invoke an action.
addTodo('Drink coffee');

// Render a component.
const TodoSummary = () => {
  const { todos } = useTodoList();
  return (
    <div>{todos.length}</div>
  );
}

// Render your app.
const App = () => (
  <Provider>
    <TodoSummaryConnected />
  </Provider>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment