Search code examples
reactjsreact-routerreact-reduxreact-router-reduxreact-router-dom

Confusion react-router-dom and react-router-redux


I'm new to react and redux, I started out my project with the react-router-dom, now I'm looking to add Redux in the mix.

Should I keep using react-router-dom or just install react-router-redux? or both? Does the Route component work the same? I'm a bit confused as what the use of react-router-dom would be?

Do I switch all the Link components to an a element that dispatches an action to the store?

Thanks for any help.


Solution

  • Generally when using Redux, it's recommended to use react-router-redux, which encapsulates react-router.

    Only when you initialize your app, you should pass a couple of things from react-router to Redux, which are Router and browserHistory.

    In app.js:

    import { Router, browserHistory } from 'react-router';
    import { syncHistoryWithStore } from 'react-router-redux';
    
    const initialState = {};
    const store = configureStore(initialState, browserHistory);
    
    const history = syncHistoryWithStore(browserHistory, store);
    
    const render = () => {
      ReactDOM.render(
        <Provider store={store}>
            <Router
              history={history}
              routes={rootRoute}
            />
        </Provider>,
        document.getElementById('app')
      );
    };
    

    You provide the Router element of react as a child of Redux's Provider element, and you also provide to the Router element the Redux wrapper for React's browserHistory.

    In the rest of your project, you only need to use react-router-redux, rather than calling React directly.

    react-router-dom BTW is just another layer of simplification in React 4 which encapsulates react-router, but in case your project architecture is Redux, than you need to work according to the rules of Redux and therefore only use react-router-redux in order to pass through the store in each action (except for the aforementioned initialization).