All Projects → CJY0208 → React Router Cache Route

CJY0208 / React Router Cache Route

Route with cache for React-Router like <keep-alive/> in Vue

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to React Router Cache Route

Cached
Rust cache structures and easy function memoization
Stars: ✭ 530 (-21.71%)
Mutual labels:  cache
Carlos
A simple but flexible cache
Stars: ✭ 564 (-16.69%)
Mutual labels:  cache
Retrofitcache
RetrofitCache让retrofit2+okhttp3+rxjava配置缓存如此简单。通过注解配置,可以针对每一个接口灵活配置缓存策略;同时让每一个接口方便支持数据模拟,可以代码减小侵入性,模拟数据可以从内存,Assets,url轻松获取。
Stars: ✭ 647 (-4.43%)
Mutual labels:  cache
Go Cache
An in-memory key:value store/cache (similar to Memcached) library for Go, suitable for single-machine applications.
Stars: ✭ 5,676 (+738.4%)
Mutual labels:  cache
Gf
GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang.
Stars: ✭ 6,501 (+860.27%)
Mutual labels:  cache
Axios Extensions
🍱 axios extensions lib, including throttle, cache, retry features etc...
Stars: ✭ 594 (-12.26%)
Mutual labels:  cache
Androidvideocache
Cache support for any video player with help of single line
Stars: ✭ 4,849 (+616.25%)
Mutual labels:  cache
Universal
Seed project for Angular Universal apps featuring Server-Side Rendering (SSR), Webpack, CLI scaffolding, dev/prod modes, AoT compilation, HMR, SCSS compilation, lazy loading, config, cache, i18n, SEO, and TSLint/codelyzer
Stars: ✭ 669 (-1.18%)
Mutual labels:  cache
Valuestore
Easily store some values
Stars: ✭ 560 (-17.28%)
Mutual labels:  cache
Cache Loader
[DEPRECATED] Caches the result of following loaders on disk
Stars: ✭ 630 (-6.94%)
Mutual labels:  cache
React Esi
React ESI: Blazing-fast Server-Side Rendering for React and Next.js
Stars: ✭ 537 (-20.68%)
Mutual labels:  cache
Bloom
🌸 HTTP REST API caching middleware, to be used between load balancers and REST API workers.
Stars: ✭ 553 (-18.32%)
Mutual labels:  cache
Httpcache
A Transport for http.Client that will cache responses according to the HTTP RFC
Stars: ✭ 603 (-10.93%)
Mutual labels:  cache
Laravel Eloquent Query Cache
Adding cache on your Laravel Eloquent queries' results is now a breeze.
Stars: ✭ 529 (-21.86%)
Mutual labels:  cache
Laravel Repositories
[ABANDONED] Rinvex Repository is a simple, intuitive, and smart implementation of Active Repository with extremely flexible & granular caching system for Laravel, used to abstract the data layer, making applications more flexible to maintain.
Stars: ✭ 664 (-1.92%)
Mutual labels:  cache
Bigcache
Efficient cache for gigabytes of data written in Go.
Stars: ✭ 5,304 (+683.46%)
Mutual labels:  cache
Flask Caching
A caching extension for Flask
Stars: ✭ 582 (-14.03%)
Mutual labels:  cache
Reservoir
Android library to easily serialize and cache your objects to disk using key/value pairs.
Stars: ✭ 674 (-0.44%)
Mutual labels:  cache
Nebulex
In-memory and distributed caching toolkit for Elixir.
Stars: ✭ 662 (-2.22%)
Mutual labels:  cache
Boltons
🔩 Like builtins, but boltons. 250+ constructs, recipes, and snippets which extend (and rely on nothing but) the Python standard library. Nothing like Michael Bolton.
Stars: ✭ 5,671 (+737.67%)
Mutual labels:  cache

CacheRoute

size dm

English | 中文说明

Route with cache for react-router like keep-alive in Vue.

Online Demo

If you want <KeepAlive /> only, try react-activation

React v15+

React-Router v4+



Problem

Using Route, component can not be cached while going forward or back which lead to losing data and interaction


Reason & Solution

Component would be unmounted when Route was unmatched

After reading source code of Route we found that using children prop as a function could help to control rendering behavior.

Hiding instead of Removing would fix this issue.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Route.js#L41-L63


Install

npm install react-router-cache-route --save
# or
yarn add react-router-cache-route

Usage

Replace Route with CacheRoute

Replace Switch with CacheSwitch (Because Switch only keeps the first matching state route and unmount the others)

import React from 'react'
import { HashRouter as Router, Route } from 'react-router-dom'
import CacheRoute, { CacheSwitch } from 'react-router-cache-route'

import List from './views/List'
import Item from './views/Item'

const App = () => (
  <Router>
    <CacheSwitch>
      <CacheRoute exact path="/list" component={List} />
      <Route exact path="/item/:id" component={Item} />
      <Route render={() => <div>404 Not Found</div>} />
    </CacheSwitch>
  </Router>
)

export default App

CacheRoute props

name type default description
when String / Function "forward" Decide when to cache
className String - className prop for the wrapper component
behavior Function cached => cached ? { style: { display: "none" }} : undefined Return props effective on the wrapper component to control rendering behavior
cacheKey String / Function - For imperative control caching
multiple (React v16.2+) Boolean / Number false Allows different caches to be distinguished by dynamic routing parameters. When the value is a number, it indicates the maximum number of caches. When the maximum value is exceeded, the oldest updated cache will be cleared.
unmount (UNSTABLE) Boolean false Whether to unmount the real dom node after cached, to save performance (Will cause losing the scroll position after recovered, fixed with saveScrollPosition props)
saveScrollPosition (UNSTABLE) Boolean false Save scroll position

CacheRoute is only a wrapper component that works based on the children property of Route, and does not affect the functionality of Route itself.

For the rest of the properties, please refer to https://reacttraining.com/react-router/


About when

The following values can be taken when the type is String

  • [forward] Cache when forward behavior occurs, corresponding to the PUSH or REPLACE action in react-router
  • [back] Cache when back behavior occurs, corresponding to the POP action in react-router
  • [always] Always cache routes when leave, no matter forward or backward

When the type is Function, the component's props will be accepted as the first argument, return true/false to determine whether to cache.


CacheSwitch props

name type default description
which Function element => element.type === CacheRoute <CacheSwitch> only saves the first layer of nodes which type is CacheRoute by default, which prop is a function that would receive a instance of React Component, return true/false to decide if <CacheSwitch> need to save it, reference #55

Lifecycles

Hooks

use useDidCache and useDidRecover to inject customer Lifecycle didCache and didRecover

import { useDidCache, useDidRecover } from 'react-router-cache-route'

export default function List() {

  useDidCache(() => {
    console.log('List cached 1')
  })

  // support multiple effect
  useDidCache(() => {
    console.log('List cached 2')
  })

  useDidRecover(() => {
    console.log('List recovered')
  })

  return (
    // ...
  )
}

Class Component

Component with CacheRoute will accept one prop named cacheLifecycles which contains two functions to inject customer Lifecycle didCache and didRecover

import React, { Component } from 'react'

export default class List extends Component {
  constructor(props) {
    super(props)

    props.cacheLifecycles.didCache(this.componentDidCache)
    props.cacheLifecycles.didRecover(this.componentDidRecover)
  }

  componentDidCache = () => {
    console.log('List cached')
  }

  componentDidRecover = () => {
    console.log('List recovered')
  }

  render() {
    return (
      // ...
    )
  }
}

Drop cache

You can manually control the cache with cacheKey prop and dropByCacheKey function.

import CacheRoute, { dropByCacheKey, getCachingKeys } from 'react-router-cache-route'

...
<CacheRoute ... cacheKey="MyComponent" />
...

console.log(getCachingKeys()) // will receive ['MyComponent'] if CacheRoute is cached which `cacheKey` prop is 'MyComponent'
...

dropByCacheKey('MyComponent')
...

Clear cache

You can clear cache with clearCache function.

import { clearCache } from 'react-router-cache-route'

clearCache()
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].