In this article, we will compare the syntax for the most famous state management library in both ecosystems — Redux & Vuex.

Agenda

  • Create-Store
  • Action
  • Async-Action
  • Reducer | Mutation
  • Combine-Reducers | Modules
  • Connect-with-Component
  • Middleware | Plugin
  • Selector | Getter
  • DevTools

Create Store

Redux: https://redux.js.org/basics/store

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
const store = createStore(todoApp)
render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Vuex: https://vuex.vuejs.org/guide/

const store = new Vuex.Store({
  state: { ... },
  mutations: { ... }
})
...
new Vue({
  el: '#app',
  store,
});

Action

Redux: https://redux.js.org/basics/actions

const ADD_TODO = 'ADD_TODO'

function addTodo(text) {
  return {
    type: ADD_TODO,
    text,
  }
}

Vuex: https://vuex.vuejs.org/guide/actions.html

const store = new Vuex.Store({
  actions: {
    increment (context) {
      context.commit('increment') // commit a mutation to trigger state update
    }
  }
})

Async-Action

Redux(redux-thunk): https://redux.js.org/advanced/async-actions

// apply redux-thunk
import thunkMiddleware from 'redux-thunk'

const store = createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware)
)
...
export function fetchPosts() {
  return function (dispatch) {
    dispatch(requestPosts())
    return fetch('xxx')
      .then(response => response.json())
      .then(json => dispatch(receivePosts(json)))
  }
}

Vuex: https://vuex.vuejs.org/guide/actions.html

actions: {
  async fetchPosts ({ commit }) {
    commit('requestPosts');
    const res = await fetch('xxx');
    commit('receivePosts', res);
  },
}

#vuex #reselect #react-redux #redux #react #programming

React and Vue Syntax Comparison Side by Side: State Management
1.25 GEEK