redux-first-router, migrate from redux-little-router, for React/Redux SPA

This is a simple tutorial showing how to switch from redux-little-router to redux-first-router. The settings are pretty similar so the changes should be easy to understand.

For more information about comparison of the 2 router packages, check out my other post redux-first-router vs redux-little-router for React/Redux SPA

Get started

Goal: To use  redux-first-router.

Base project code: Example code from React Routing with redux-little-router, ASP.NET Core SPA will be used as starting point. (Rendering a simple HelloWorld component)

Base project structure:

Npm packages

Add the following package inside “dependencies” in file package.json

Setup Routes

Replace  routes.tsx in folder Scripts as follow:

routes defines all the routes with name (redux action type) maps to their URL. It is used by redux-first-router to perform the routing.

App is a  React functional component that defines the SPA.

Page is a connected  React component provided to display the corresponding page based on the route name defined at state.location.type.

Link is another React component that lets you change route through hyperlink.

Update HelloWorld component

Simply removed the componentWillMount() method of HelloWorld component.

Data fetching for HelloWorld component ( retrieveData()) is declared as an optional thunk for the HOME route. Therefore, when HOME page is shown, retrieveData() is automatically called at client side. As a result, componentWillMount() is no longer needed.

Boilerplate for client side rendering

Replace the entry point  entry.tsx as follow:

By calling connectRoutes() from redux-first-router, we get a reducer, middleware and enhancer for use to configure the Redux store.

Boilerplate for server side rendering

Replace the entry point entry-server.tsx as follow:

The change is similar to that of client side except history is created using createMemoryHistory() instead. Note that connectRoutes() also returns a thunk (the optional thunk associated with the route, if any). At server side, we need to call it manually by passing the redux Store as an argument.  addTask() and params.domainTasks are used to ensure any async operations (data fetching) are completed before calling renderToString() to render the page.

Note that in this example, the data fetching for HelloWorld inside component is no longer needed. As a result, renderToString() is only called once.


Example code is available at Github.

Leave a Reply

Your email address will not be published. Required fields are marked *