Similar to Vue keep-alive, But it is not a component.
npm i use-keep-state -S
No.1 Demo
import React from 'react';
import useKeepState from 'use-keep-state';
// Must be unique
const namespace = 'App';
const initState = {
number: 0
};
const App = () => {
const [state, setState] = useKeepState(initState, namespace);
const onClick = () => {
setState({ number: state.number + 1 });
};
return (
<div>
<h1>{state.number}</h1>
<button onClick={onClick}>Click</button>
</div>
)
}
export default App;
No.2 Demo
import React from 'react';
import useKeepState from 'use-keep-state';
// Must be unique
const namespace = 'App';
const initState = {
number: 0
};
const App = () => {
const [state, setState, destroyState] = useKeepState(initState, namespace);
const onClick = () => {
setState({ number: state.number + 1 });
};
React.useEffect(() => {
// Leave reset state
return () => destroyState(namespace);
}, []);
return (
<div>
<h1>{state.number}</h1>
<button onClick={onClick}>Click</button>
</div>
)
}
export default App;
useKeepState(initState: object, [options]: object | string)
options
- namespace // Unique name
String
- keepAlive // default
true
- sessionStorage // default
false
MIT