Reputation: 19839
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?
Upvotes: 96
Views: 116543
Reputation: 5902
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:
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']);
Upvotes: 79
Reputation: 1
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>
Upvotes: 0
Reputation: 2365
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
Upvotes: 0
Reputation: 908
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.
Upvotes: 0
Reputation: 456
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.
Upvotes: 2
Reputation: 8961
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 (...)
}
Upvotes: 8
Reputation: 393
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:
Upvotes: 21
Reputation: 17132
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.
Upvotes: 12
Reputation: 484
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).
Upvotes: 4
Reputation: 2217
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.
Upvotes: 2
Reputation: 19839
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 :)
Upvotes: 34
Reputation: 1758
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.
Upvotes: 0