react-next-keep-alive
Version:
Module for caching views in next.js
39 lines (38 loc) • 1.44 kB
TypeScript
/**
* Keep alive component
* https://stackoverflow.com/questions/59124463/nextjs-how-to-not-unmount-previous-page-when-going-to-next-page-to-keep-state
*
* Tried following libraries before implementing this one:
* - react-keep-alive: has a lot of dom manipulation bugs and crashes our app
* - react-activation: does not handle SSR correctly
* - there are some others but they are built on react-router, which next.js doesn't use
*
* Basic Usage:
* 1) Wrap nextjs <Component /> with <KeepAliveProvider> in _app.tsx
* 2) Wrap components export with "withKeepAlive" and provide unique name like this: export default withKeepAlive(IndexPage, 'index');
*/
import React, { ReactElement } from 'react';
import { NextRouter } from 'next/router';
type KeepAliveNameFnArgs = {
props: any;
router: NextRouter;
};
export type KeepAliveName = string | ((nameArgs: KeepAliveNameFnArgs) => string);
export type KeepAliveOptsProps = {
keepScrollEnabled?: boolean;
applyNewProps?: boolean | ((cachedProps: any, newProps: any) => Object);
};
type KeepAliveData = {
name: KeepAliveName;
} & KeepAliveOptsProps;
type ExtendChildrenType = {
type: {
keepAlive: KeepAliveData;
};
};
type KeepAliveProviderProps = {
children: ReactElement & ExtendChildrenType;
router: NextRouter;
};
declare const KeepAliveProvider: (props: KeepAliveProviderProps) => React.JSX.Element;
export default KeepAliveProvider;