3.0.0 ā€¢ Published 8 months ago

react-redux-history v3.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

build license npm minsize

āš› Navigation history made easy!

Lots of applications need more control over their navigation than what their router provides

No worries, we are here to help

Compatible with both react-router v6 and v5 API

šŸ“œ Save all navigation history in store Ā  Get started

šŸŒ² Persist history after reloading the page Ā  Read more

ā­ļø Skipping screens capability out of the box Ā  Read more

šŸ”€ Dispatch location changes Ā  Read more

šŸ‘Š Force current route to re-render Ā  Read more

šŸš¦ Selectors for easy access Ā  Read more

šŸ› Easy debug, find everything you need to know about navigation in your favorite dev tools:

Setup

Step 1)

Let's get started by installing the package:

pnpm add react-redux-history
npm i react-redux-history
yarn add react-redux-history

Step 2)

Create a browser router and pass it to configureRouterHistory. The returned reducer and middleware will be used to connect to the store:

// store.js
import { configureRouterHistory } from 'react-redux-history'
import { createBrowserRouter } from 'react-router-dom'
import { routes } from 'src/routes'

// optional, defaults are listed below
const options = {
  storageKey: 'routerState',
  storageLimit: Infinity
}

export const router = createBrowserRouter(routes);
export const { routerReducer, routerMiddleware } = configureRouterHistory({ router, ...options })

Backwards compatibility with react-router legacy v5 API is also supported:

// store.js
import { configureRouterHistory } from 'react-redux-history'
import { createBrowserHistory } from 'history'

const options = { ... }

export const history = createBrowserHistory() // react-router legacy v5 API
export const { routerReducer, routerMiddleware } = configureRouterHistory({ history, ...options })

For more info regarding differences between react-router v5 and v6 API check out the official docs

Step 3)

Add the reducer and middleware to your store. If you are using Redux Toolkit it should look something like this:

// store.js
const store = configureStore({
  reducer: combineReducers({
    // ...other reducers
    router: routerReducer
  }),
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware()
      // ...other middleware
      .concat(routerMiddleware)
})

export default store

Step 4)

Lastly, add either <LocationListener /> or useLocationListener somewhere at the root of your app:

// App.tsx
import { useLocationListener, LocationListener } from 'react-redux-history'
// use the `history` object if working with `react-router` v5 API
import { router } from 'src/store'

const App = () => {
  useLocationListener(router) // use either this or the component below, not both!
  
  return (
    <>
      ...
      <LocationListener router={router} /> 
      ...
    </>
  )
}

Note: the router / history objects provided to configureRouterHistory and useLocationListener / LocationListener must be the same objects !

Configuration

The middleware can be configured by passing an options object as the second argument to configureRouterHistory.

The following options are available:

  • storageKey - the key to use when saving the state to session storage. Defaults to routerState
  • storageLimit - the maximum number of entries to save in session storage. Defaults to Infinity

Be careful when limiting session storage entries. The user is still able to go back to previous pages even if they are not saved in session storage. This can cause unexpected behaviour on page reload, especially if you use skipBack / skipForward or similar logic that alters the navigation flow.

Features

šŸŒ² Persistent history

History is persisted after page refresh by leveraging session storage.

This helps provide a better user experience and allows you to build a more robust navigation system.

ā­ļø Skip back / forward

By setting a skipBack / skipForward flag on a specific route the user will be automatically skipped over certain routes.

history.push({
  pathname: 'page_5',
  state: { skipBack: 4 }
})

In this example, every time the user will try to go back from page_5 he will be skipped back 4 pages, reaching page_1. The same behaviour will apply when going forward from page_1, the user will be skipped forward to page_5.

Note: Due to the restrictive nature of browser navigation, back or forward actions cannot be stopped. That means that in the previous example the user will actually reach page_4 before being redirected to page_1. If there is conflicting logic (such as extra redirects) in page_4, it will be fired before the middleware manages to completely skip all screens. In order to get past this issue we can selectIsSkipping to not render the component tree while skipping.

We managed this at Utilmond by leveraging the selector in our general purpose loading component. When the flag is true, we render a loading backdrop instead of the current route. This prevents any conflicting logic to be fired and mess with the redirects.

šŸ”€ Dispatch location changes

Change current location using redux actions anywhere in your app.

The API is compatible with history, it can be used as a drop-in replacement.

import { push, replace, forward, back, go } from 'react-redux-history'

dispatch(push({
  pathname: 'homepage',
  state: {
    ...
  }
}))

// or use the short version

dispatch(push('homepage'))

šŸ‘Š Force current route to re-render

Force current route to re-render by using selectForceRender. Navigate to the same route while passing forceRender: {} in location state.

import { useSelector } from 'react-redux'
import { selectForceRender } from 'react-redux-history'

const Component = () => {
  // The component will re-render every time the `forceRender` flag reference changes
  const forceRender = useSelector(selectForceRender)

  useEffect(() => {
    // The flag can also be used as a dependency in order to re-trigger effects
  }, [forceRender])

  return (
    <button
      onClick={() => {
        history.push({
          // By default `react-router` will not trigger re-rendering when the pathname is the same
          pathname: 'current_pathname',
          state: {
            // Simply pass a new object to force re-rendering
            forceRender: {}
          },
        })
      }}
    >
      Re-render
    </button>
  )
}

šŸš¦ Selectors for easy access

There are also a few useful selectors for easy access:

  • selectLocationHistory
  • selectCurrentLocation
  • selectCurrentLocationState
  • selectCurrentLocationIndex
  • selectNextLocation
  • selectPreviousLocation
  • selectBackLocation
  • selectHistoryAction
  • selectIsSkippingRoutes
  • selectIsNewSession
  • selectForceRender

šŸš€ Powered by

Used in production by Utilmond

react redux react-router

3.0.0

8 months ago

2.1.16

8 months ago

3.0.0-rc.2

8 months ago

2.1.14

12 months ago

2.1.15

11 months ago

2.1.12

12 months ago

2.1.13

12 months ago

2.1.10

12 months ago

2.1.11

12 months ago

1.2.0

1 year ago

1.2.0-1

1 year ago

1.2.0-0

1 year ago

1.4.1

1 year ago

1.4.0

1 year ago

1.2.2

1 year ago

1.2.1

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.5

12 months ago

2.0.4

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

2.1.9

12 months ago

1.0.0-0

1 year ago

1.5.8

1 year ago

1.5.7

1 year ago

1.5.6

1 year ago

1.1.0

1 year ago

1.5.5

1 year ago

1.5.4

1 year ago

1.5.3

1 year ago

1.5.2

1 year ago

1.5.1

1 year ago

1.5.0

1 year ago

1.5.0-3

1 year ago

1.3.0

1 year ago

2.1.2

12 months ago

2.1.1

12 months ago

2.1.4

12 months ago

2.1.3

12 months ago

2.1.6

12 months ago

2.1.5

12 months ago

2.1.8

12 months ago

2.1.7

12 months ago

2.1.0

12 months ago

1.4.0-0

1 year ago

3.0.0-rc.1

12 months ago

1.5.0-2

1 year ago

1.5.0-1

1 year ago

1.5.0-0

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.1-0

1 year ago

0.1.8

2 years ago

0.1.7

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.4

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago