npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

keepalive-for-react

v2.0.7

Published

A react <KeepAlive/> component like <keep-alive/> in vue, it can cache component state when component unmount, and restore state when component mount again.

Downloads

500

Readme

KeepAlive for React

中文 | English

NPM版本 NPM下载

介绍

一个类似于Vue中keep-alive的React KeepAlive组件

注意!

  • 请勿使用 <React.StrictMode />,它无法在开发模式下与keepalive-for-react协同工作。因为当你使用keepalive-for-react的useOnActive钩子时,它可能会导致一些意外行为。

  • 在Router中仅支持react-router-dom v6+ 版本

特性

  • 支持react 16.8+ ~ 18+
  • 显著减少页面中的DOM元素数量
  • 支持缓存组件状态
  • 简单实现,无需任何额外依赖和黑客方法
  • 支持自定义缓存规则
  • 高性能,无性能损失
  • 易于使用,只需包装你想要缓存的组件

使用方法

安装

npm

npm install --save keepalive-for-react 

API

KeepAlive

在简单的标签页中

import KeepAlive from 'keepalive-for-react';

function TabsPage() {
  const tabs = [
    {name: 'Tab1', cache: true, component: Tab1,},
    {name: 'Tab2', cache: true, component: Tab2,},
    {name: 'Tab3', cache: false, component: Tab3,},
  ];
  const [activeTab, setActiveTab] = useState('Tab1');

  const page = useMemo(() => {
    return tabs.find(tab => tab.name === activeTab);
  }, [activeTab]);

  return   <div>
    <KeepAlive
      max={20} strategy={'PRE'} activeName={activeTab} cache={page?.cache}
    >
      {page && <page.component name={page.name} />}
    </KeepAlive>
  </div>
}

在react-router-dom中 v6+

import {useLocation, useOutlet} from 'react-router-dom';

function BasicLayoutWithCache() {
  
  const outlet = useOutlet();
  const location = useLocation();


  /**
   * 用于区分不同页面以进行缓存
   */
  const cacheKey = useMemo(() => {
    return location.pathname + location.search;
  }, [location]);


  return <div>
    <KeepAlive activeName={cacheKey} max={10} strategy={'LRU'}>
      {outlet}
    </KeepAlive>
  </div>
}

useEffectOnActive / useLayoutEffectOnActive

useEffectOnActive是一个钩子,用于监听被KeepAlive包装的组件的激活状态。


import {useEffectOnActive} from 'keepalive-for-react';

useEffectOnActive((active) => {
    console.log('useOnActive', active);
}, false, []);

useKeepAliveContext

useKeepAliveContext是一个钩子,用于获取KeepAlive CacheComponent上下文。

import {useKeepAliveContext} from 'keepalive-for-react';

function CachedComponent() {
  
  const { active, destroy} = useKeepAliveContext();
  // active: boolean, 组件是否激活
  // destroy: () => void, 从缓存中销毁组件

  // ...
}

KeepAlive Props

interface Props {
  children: ReactNode;
  /**
   * active name
   */
  activeName: string;
  /**
   * max cache count default 10
   */
  max?: number;
  /**
   * cache: boolean default true
   */
  cache?: boolean;
  /**
   * maxRemoveStrategy: 'PRE' | 'LRU' default 'PRE'
   *
   * PRE: remove the first cacheNode
   *
   * LRU: remove the least recently used cacheNode
   */
  strategy?: 'PRE' | 'LRU';
  /**
   * aliveRef: KeepAliveRef
   *
   * aliveRef is a ref to get caches, remove cache by name, clean all cache, clean other cache except current
   *
   */
  aliveRef?: RefObject<KeepAliveRef | undefined> | MutableRefObject<KeepAliveRef | undefined>;

  exclude?: Array<string | RegExp> | string | RegExp;

  include?: Array<string | RegExp> | string | RegExp;

  /**
   * suspenseElement: Suspense Wrapper Component
   */
  suspenseElement?: ComponentType<{
    children: ReactNode,
  }>;

  /**
   *  errorElement: for every cacheNode's ErrorBoundary 
   */
  errorElement?: ComponentType<{
    children: ReactNode,
  }>;
}

type KeepAliveRef = {
  getCaches: () => Array<CacheNode>

  removeCache: (name: string) => void

  cleanAllCache: () => void

  cleanOtherCache: () => void
}

useKeepaliveRef

import { useKeepaliveRef } from "keepalive-for-react"

function Example() {

    const aliveRef = useKeepaliveRef()
    
    function clean(){
        aliveRef.current?.cleanAllCache()
    }
    // ...
    
    return <KeepAlive aliveRef={aliveRef} >
        ...
    </KeepAlive>
}

完整代码使用示例

链接到 React Keepalive Demo Repo

在线预览Demo: 链接: https://irychen.github.io/react-keepalive-demo/