Skip to content

mousejs/use-keep-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


useKeepState

Similar to Vue keep-alive, But it is not a component.

Stars Badge

Example

codesandbox

Install

npm i use-keep-state -S

Example

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;

API

useKeepState(initState: object, [options]: object | string)

options

  • namespace // Unique name String
  • keepAlive // default true
  • sessionStorage // default false

License

MIT