I have a simple component that maintains an internal state. I have another component that toggles whether or not <
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:
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']);