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?
Summary. Seeing called setState() on an unmounted component in your browser console means the callback for an async operation is still running after a component's removed from the DOM. This points to a memory leak caused by doing redundant work which the user will never benefit from.
The warning "Can't perform a React state update on an unmounted component" is caused when we try to update the state of an unmounted component. A straight forward way to get rid of the warning is to keep track of whether the component is mounted using an isMounted boolean in our useEffect hook.
To maintain state after a page refresh in React, we can save the state in session storage. const Comp = () => { const [count, setCount] = useState(1); useEffect(() => { setCount(JSON. parse(window. sessionStorage.
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']);
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With