Code

MOBX to Redux-Toolkit

Ever since React Introduced Hooks it is more elegant to simply write functional components.

Today I will transition my MOBX example Project to Redux or more specifically Redux-Toolkit an opinionated redux toolset.

Add Packages

Instead of using Redux directly, it is much easier to use the opinionated redux toolkit, also created by the redux team.

Additionally we need to get react-redux to connect redux to react.

npm install @reduxjs/toolkit
npm install react-redux

Basic initialization

During the transition period MOBX and Redux can be used in parallel. This is of course not a state you will want to keep for a long time.

First we need to add to index.ts a redux Store. For now without any reducers thus an empty object {}. We will add a reducer later.

stores/index.ts

// (MOBX imports)
import { configureStore } from '@reduxjs/toolkit';

//(... MOBX Code)

export const reduxStore = configureStore({
  reducer: {},
});

We now need to add a redux provider to our index.ts. This will cause a nameclash with the mobx Provider. By using the as Keyword we can just rename it for no as ReduxProvider.

Your code should look something like this:

index.ts

import { Provider } from 'mobx-react';
import { stores } from './stores';
import { Provider as ReduxProvider } from 'react-redux';
import { exampleReducer } from './stores/exampleReducer';

ReactDOM.render(
  <ReduxProvider store={exampleReducer}>
    <Provider {...stores}>
      <App />
    </Provider>
  </ReduxProvider>,

  document.getElementById('root'),
);

Initializing our first reducer

Now initially you might think you should use the createReducer to create a reducer. However redux-toolkit provides you with a more useful createSlice() function. Read more about it here.