How to keep React component state between mount/unmount?

后端 未结 8 1653
心在旅途
心在旅途 2020-12-12 18:15

I have a simple component that maintains an internal state. I have another component that toggles whether or not <

8条回答
  •  清歌不尽
    2020-12-12 18:29

    Since you can't keep the state in the component itself when it unmounts, you have to decide where else it should be saved.

    These are your options:

    1. React state in parent: If a parent component remains mounted, maybe it should be the owner of the state or could provide an initial state to an uncontrolled component below. You can pass the value back up before the component unmounts. With React context you can hoist the state to the very top of your app (see e.g. unstated).
    2. Outside of React: E.g. use-local-storage-state. Note that you might need to manually reset the state inbetween tests. Other options are query params in the URL, state management libraries like MobX or Redux, etc.

    I've you're looking for an easy solution where the data is persisted outside of React, this Hook might come in handy:

    const memoryState = {};
    
    function useMemoryState(key, initialState) {
      const [state, setState] = useState(() => {
        const hasMemoryValue = Object.prototype.hasOwnProperty.call(memoryState, key);
        if (hasMemoryValue) {
          return memoryState[key]
        } else {
          return typeof initialState === 'function' ? initialState() : initialState;
        }
      });
    
      function onChange(nextState) {
        memoryState[key] = nextState;
        setState(nextState);
      }
    
      return [state, onChange];
    }
    

    Usage:

    const [todos, setTodos] = useMemoryState('todos', ['Buy milk']);
    

提交回复
热议问题