简体   繁体   中英

How to keep React component state between mount/unmount?

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?

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 eg unstated ).
  2. Outside of React : Eg 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']);

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

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.

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.

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

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 .

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 (ie 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 (...)
}

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.

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.

I came across this post looking for a way to build the component state over time, ie, 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 eg, length.

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, eg with NextJS it would be

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM