react-router-refreshable
Supports refresh (remount) on react-router-dom
Install
npm i react-router-refreshable
Example
import { Refreshable } from 'react-router-refreshable'
<Layout>
<Refreshable>
<Switch>
<Route path="/home">
<HomePage />
</Route>
<Route path="/post">
<PostPage />
</Route>
{/* ... */}
</Switch>
</Refreshable>
</Layout>
Description
When the user clicks on a link with the same url as the current url on the react-router, nothing happens. However, most users expect the page to refresh. Solving with location.reload()
(or <BrowserRouter forceRefresh />
) is wasteful.
The Refreshable
component of react-router-refreshable
remounts children
when history.push
to the same url. It is possible to efficiently provide the user's expected result.
See a Demo
Nested Refreshable
Each page may have different areas to expect to refresh. Nested Refreshables can dynamically narrow the refresh area.
<Refreshable>
<Route path="/teams/:teamId">
{/* 👇 This component is not refreshed. */}
<TeamsContentLayout>
<Refreshable>
<TeamPageHeader /> {/* 👈 This component can be refreshed. */}
</Refreshable>
{/* ... */}
<Refreshable>
<TeamPageContent /> {/* 👈 This component can be refreshed. */}
</Refreshable>
</TeamsContentLayout>
</Route>
{/*...*/}
</Refreshable>
on
event listener prop
There is an on
property that triggers when the refresh is started.
<Refreshable on={() => console.log('Start refreshing!')}>{/* ... */}</Refreshable>
useIsRefreshingRef()
useIsRefreshingRef()
returns a RefObject
indicating whether it is refreshing. Although not recommended, ignoring some logic in the effects hook can improve performance.
import { useIsRefreshingRef } from 'react-router-refreshable'
function Page() {
const isRefreshingRef = useIsRefreshingRef()
useEffect(() => {
if (!isRefreshingRef.current) {
/* ... Run only when not refresh */
}
return () => {
if (!isRefreshingRef.current) {
/* ... Run only when not refresh */
}
}
}, [])
/* ... */
}
License
MIT