93

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?

2
  • 1
    you could store the state on a Store using Flux Commented Jul 11, 2015 at 0:40
  • yeah, I was trying not to have save/load methods. Also, this could get tricky for me. Think about this in the context of a UINavigationController -- I may have multiple of the same exact component, but with different states, at different levels in the navigation stack...
    – Chet
    Commented Jul 11, 2015 at 0:42

12 Answers 12

79

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

Consider these 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 in between tests. Other options are query params in the URL, state management libraries like MobX or Redux, etc.

If 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']);
2
  • 10
    Just a warning to others this is not going to work with testing or Components that get used in more than one spot.
    – pllee
    Commented Dec 1, 2017 at 18:52
  • @pllee not necessarily - if you're using meaningful IDs. For instance - the component using state could generate its ID on mount, like GUID. Then you'd call this function like: const [todos, setTodos] = useMemoryState('guid-here', ['Buy milk']); And possibly, for different variables, this could be extended to: const [todos, setTodos] = useMemoryState('guid-here', 'todos', ['Buy milk']); const [numbers, setNumbers] = useMemoryState('guid-here', 'numbers', [1, 42]); Commented Aug 25, 2022 at 19:53
34

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.

2) 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.

3) 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 :)

2
  • 1
    This looks exactly like something I would need. Could you elaborate a bit more? Give an example of storing the state of component and restoring it in real life?
    – Cubelaster
    Commented Nov 15, 2018 at 11:04
  • This is a great fix, Thanks Commented Nov 25, 2019 at 17:15
21

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.
3
  • I had the same situation, I didn't go for persist library just because I wanted a common pattern which should happen even if the users are different. Just use redux Commented Feb 4, 2020 at 10:34
  • 1
    all of them are equivalent and share the same issues. Storing state in Redux still does not solve the problem of the instance
    – albanx
    Commented Jul 12, 2021 at 16:42
  • This should be a comment
    – Mr. N
    Commented Oct 6, 2023 at 20:24
12

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.

5
  • localStorage is interesting concept for web, will give it a go. Thanks Commented Feb 18, 2018 at 20:16
  • 1
    localStorage is secure. You can store up to about 15 MB of data in it, depending on browser, etc. It works very well for short term persistent data.
    – agm1984
    Commented Feb 28, 2018 at 5:10
  • How about performance? Does it take time to read/write local storage compared to mutating global state of react app? muting state potentially rerender a whole lot of components which is why I am also looking for a solution to save a single components state between unmount/mount. But only in a performant way. Commented Dec 18, 2019 at 10:38
  • I would say performance is the secondary main concern after just getting the data to persist through dismounts. Storing data in upstream components is basically "lifting state" in React. This is more performant than saving data to disk because you are changing the reference to the data in-memory and basically avoiding garbage collection, so read/write speed will be turbo; however, storing the data in localStorage allows the data to persist as the root component itself is unmounted and remounted.
    – agm1984
    Commented Dec 18, 2019 at 21:41
  • componentWillMount is deprecating so replace with componentDidMount :) Commented Jun 11, 2022 at 2:13
8

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 (...)
}
1
  • 1
    If going this way, you can actually make use of useId by creating a mini "store" -> const cachedState = new Map<string, unknown>(), then use const id = useId(), then get state by cachedState.get(id, state) and set by cachedState.set(id, state). so a cached state is not shared between multiple instances but have their own.
    – FrameMuse
    Commented Nov 16, 2022 at 16:22
4

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).

2

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.

2

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.

2
  • This isn't open source? Commented Nov 8, 2021 at 11:32
  • I mean, I made it myself, and released it as open source, so it is!
    – Edward
    Commented Dec 14, 2021 at 18:25
0

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.

3
  • yeah, thats not what I'm getting at though. This is a contrived example so what you mention would work for this example, but not for the more complicated issue I'm trying to solve...
    – Chet
    Commented Jul 11, 2015 at 1:09
  • Your question was about maintaining the component specifically. As far as I know the best you can do is maintain the component's state and re-instantiate the component.
    – ChadF
    Commented Jul 11, 2015 at 1:11
  • I see. Thats as far as I know as well. The less contrived version is this: I'm trying to build UITabBarController and UINavigationController equivalents for the web. With the UINavigationController specifically, we can be pushing arbitrary views to the stack and popping them off. Its not really feasible to keep track of all that arbitrary state so it would be great if I could keep the state within the component itself between mounting...
    – Chet
    Commented Jul 11, 2015 at 1:15
0

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.

3
  • i tried your ref solution, but it didn't work, it lost ref values once i am out of the component and came back to component again!
    – Danish
    Commented Aug 13, 2021 at 12:09
  • The use ref saves the data on a node in the DOM. Is it possible that you are reloading the DOM? Commented Aug 13, 2021 at 14:13
  • 1
    Re-rendering and re-mounting is not the same. Commented May 25, 2022 at 14:23
0

This won't suffice for the scenario of the thread opener, but maybe for other people stumbling on this thread: Depending on how much persistence you need and how complex the data is you want to store, a query parameter might also suffice.

For example, if you just want to keep a bool hideItems between window resizing operations, it will retain if you append it in the manner of my.example.com/myPage?hideItems=true. You've got to evaluate the parameter on rendering inside you page/component, e.g. with NextJS it would be

const router = useRouter()
const hide = router.query.hideItems
0

In my case, I select items to payment and save it to state in redux store, when my component is unmout, I want to set state to new list. But I have a special case after I payment success and redirect to another page, I don't want to keep my old data, I use useRef like this

const isPayment = useRef(false)

useEffect(() => { 

return () => {
  if(!isPayment.current){
     //if my handlePayment is called, 
     // I won't run my handle when component is unmout 
    Your action when component is unmout
  }
}
},[])

const handlePayment = () => {
  isPayment.current = true

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.