How to keep React component state between mount/unmount?

JavascriptReactjs

Javascript Problem Overview


I have a simple component <StatefulView> that maintains an internal state. I have another component <App> that toggles whether or not <StatefulView> is rendered.

However, I want to keep <StatefulView>'s internal state between mounting/unmouting.

I figured I could instantiate the component in <App> and then control whether its rendered/mounted.

var StatefulView = React.createClass({
  getInitialState: function() {
    return {
      count: 0
    }
  },
  inc: function() {
    this.setState({count: this.state.count+1})
  },
  render: function() {
    return (
        <div>
          <button onClick={this.inc}>inc</button>
          <div>count:{this.state.count}</div>
        </div>
    )
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      show: true,
      component: <StatefulView/>
    }
  },
  toggle: function() {
    this.setState({show: !this.state.show})
  },
  render: function() {
    var content = this.state.show ? this.state.component : false
    return (
      <div>
        <button onClick={this.toggle}>toggle</button>
        {content}
      </div>
    )
  }
});

This apparently doesnt work and a new <StatefulView> is created on each toggle.

Here's a JSFiddle.

Is there a way to hang on to the same component after it is unmounted so it can be re-mounted?

Javascript Solutions


Solution 1 - Javascript

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']);

Solution 2 - Javascript

OK. So after talking with a bunch of people, it turns out that there is no way to save an instance of a component. Thus, we HAVE to save it elsewhere.

  1. The most obvious place to save the state is within the parent component.

This isn't an option for me because I'm trying to push and pop views from a UINavigationController-like object.

  1. You can save the state elsewhere, like a Flux store, or in some global object.

This also isn't the best option for me because it would be a nightmare keeping track of which data belongs to which view in which Navigation controller, etc.

  1. Pass a mutable object to save and restore the state from.

This was a suggestion I found while commenting in various issue tickets on React's Github repo. This seems to be the way to go for me because I can create a mutable object and pass it as props, then re-render the same object with the same mutable prop.

I've actually modified it a little to be more generalized and I'm using functions instead of mutable objects. I think this is more sane -- immutable data is always preferable to me. Here's what I'm doing:

function createInstance() {
  var func = null;
  return {
    save: function(f) {
      func = f;
    },
    restore: function(context) {
      func && func(context);
    }
  }
}

Now in getInitialState I'm creating a new instance for the component:

component: <StatefulView instance={createInstance()}/>

Then in the StatefulView I just need to save and restore in componentWillMount and componentWillUnmount.

componentWillMount: function() {
  this.props.instance.restore(this)
},
componentWillUnmount: function() {
  var state = this.state
  this.props.instance.save(function(ctx){
    ctx.setState(state)
  })
}

And that's it. It works really well for me. Now I can treat the components as if they're instances :)

Solution 3 - Javascript

For those who are just reading this in 2019 or beyond, a lot of details have already been given in the other answers, but there are a couple of things that I want to emphasize here:

  • Saving state in some store (Redux) or Context is probably the best solution.
  • Storing in global variable will only work if there is ever only ONE instance of your component at a time. (How will each instance know which stored state is theirs?)
  • Saving in localStorage has just the same caveats as global variable, and since we're not talking about restoring state on browser refresh, it doesn't seem to add any benefit.

Solution 4 - Javascript

Hmm, you could use localStorage, or AsyncStorage if React Native.

React Web

componentWillUnmount() {
  localStorage.setItem('someSavedState', JSON.stringify(this.state))
}

Then later that day or 2 seconds later:

componentWillMount() {
  const rehydrate = JSON.parse(localStorage.getItem('someSavedState'))
  this.setState(rehydrate)
}

React Native

import { AsyncStorage } from 'react-native'

async componentWillMount() {
  try {
    const result = await AsyncStorage.setItem('someSavedState', JSON.stringify(this.state))
    return result
  } catch (e) {
    return null
  }
}

Then later that day or 2 seconds later:

async componentWillMount() {
  try {
    const data = await AsyncStorage.getItem('someSavedState')
    const rehydrate = JSON.parse(data)
    return this.setState(rehydrate)
  } catch (e) {
    return null
  }
}

You could also use Redux and pass the data into the child component when it renders. You might benefit from researching serializing state and the second parameter of the Redux createStore function which is for rehydrating an initial state.

Just note that JSON.stringify() is an expensive operation, so you should not do it on keypress, etc. If you have concern, investigate debouncing.

Solution 5 - Javascript

I'm late to the party but if you're using Redux. You'll get that behaviour almost out of the box with redux-persist. Just add its autoRehydrate to the store then it will be listening to REHYDRATE actions that will automatically restore previous state of the component (from web storage).

Solution 6 - Javascript

I'm not an expert in React but particularly your case could be solved very cleanly without any mutable objects.

var StatefulView = React.createClass({
  getInitialState: function() {
    return {
      count: 0
    }
  },
  inc: function() {
    this.setState({count: this.state.count+1})
  },
  render: function() {
      return !this.props.show ? null : (
        <div>
          <button onClick={this.inc}>inc</button>
          <div>count:{this.state.count}</div>
        </div>
    )
    
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      show: true,
      component: StatefulView
    }
  },
  toggle: function() {
    this.setState({show: !this.state.show})
  },
  render: function() {
    return (
      <div>
        <button onClick={this.toggle}>toggle</button>
        <this.state.component show={this.state.show}/>
      </div>
    )
  }
});

ReactDOM.render(
  <App/>,
  document.getElementById('container')
);

You can see it at jsfiddle.

Solution 7 - Javascript

An easy way of caching state between renders would be to use the fact that modules exported form closure over the file that you are working in.

Using a useEffect hook you can specify logic that happens on component dismount (i.e. update a variable that is closed over at the module level). This works because imported modules are cached, meaning that the closure created on import never disappears. I'm not sure if this is a GOOD approach or not, but works in cases where a file is only imported once (otherwise the cachedState would be shared across all instances of the default rendered component)

var cachedState

export default () => {
  const [state, setState] = useState(cachedState || {})

  useEffect(() => {
    return () => cachedState = state
  })

  return (...)
}

Solution 8 - Javascript

I've made a simple NPM package exactly for this purpose. You can find it here:

https://www.npmjs.com/package/react-component-state-cache

Usage is simple. First, include the component somewhere high up in your component tree, like this

import React from 'react'
import {ComponentStateCache} from 'react-component-state-cache'
import {Provider} from 'react-redux' // for example
import MyApp from './MyApp.js'

class AppWrapper extends React.Component {
    render() {
        return (
            <Provider store={this.store}>
                <ComponentStateCache>
                    <MyApp />
                </ComponentStateCache>
            </Provider>
        )
    }
}

then, you can use it in any of your components as follows:

import React from 'react'
import { withComponentStateCache } from 'react-component-state-cache'

class X extends React.Component {

    constructor(props) {
        super(props)

        this.state = {
            // anything, really.
        }
    }

    componentDidMount() {
        // Restore the component state as it was stored for key '35' in section 'lesson'
        //
        // You can choose 'section' and 'key' freely, of course.
        this.setState(this.props.componentstate.get('lesson', 35))
    }

    componentDidUnmount() {
         // store this state's component in section 'lesson' with key '35'
        this.props.componentstate.set('lesson', 35, this.state)
    }

}

export default withComponentStateCache(X)

That's it. Easy peasy.

Solution 9 - Javascript

If you want to be able to unmount and mount while maintaining state, you will need to store the count in App and pass down the count via props.

(When doing this, you should be calling a toggle function inside of App, you want the functionality which changes data to live with the data).

I will modify your fiddle to be functional and update my answer with it.

Solution 10 - Javascript

I came across this post looking for a way to build the component state over time, i.e., with each additional page from the backend.

I use a persistor and redux. However, for this state I wanted to keep it local to the component. What ended up working: useRef. I'm a bit surprised no one mentioned it so I could be missing an important part of the question. Notwithstanding, the ref persists between renders of React's virtual DOM.

With that in place, I can build my cache over-time, watch the component update (aka re-render), but not worry about "throwing-out" previous api data that remains relevant for the component.

  const cacheRef = useRef([]);
  const [page, setPage] = useState(() => 0);

  // this could be part of the `useEffect` hook instead as I have here
  const getMoreData = useCallback(
    async (pageProp, limit = 15) => {

      const newData = await getData({
        sources,
        page: pageProp,
        limit,
      });

      cacheRef.current = [...(cacheRef.current || []), ...newData];
      
    },
    [page, sources],
  );

  useEffect(() => {
    const atCacheCapacity = cacheRef.current.length >= MAX;
    if (!atCacheCapacity) {
      getMoreData(page + 1);
      setPage(page + 1);
    }
  }, [MAX, getMoreData, page]);

The component is tricked into re-rendering by tracking a local state that changes with the increasing size of the cache. I don't copy the ref data on the DOM into the component's local state, just some sort of summary e.g., length.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChetView Question on Stackoverflow
Solution 1 - JavascriptamannView Answer on Stackoverflow
Solution 2 - JavascriptChetView Answer on Stackoverflow
Solution 3 - JavascriptArnel EneroView Answer on Stackoverflow
Solution 4 - Javascriptagm1984View Answer on Stackoverflow
Solution 5 - JavascriptYann VRView Answer on Stackoverflow
Solution 6 - JavascriptJames AkwuhView Answer on Stackoverflow
Solution 7 - JavascriptZach SmithView Answer on Stackoverflow
Solution 8 - JavascriptEdwardView Answer on Stackoverflow
Solution 9 - JavascriptChadFView Answer on Stackoverflow
Solution 10 - JavascriptEdmund's EchoView Answer on Stackoverflow