Skip to content

Instantly share code, notes, and snippets.

@tfiechowski
Created April 6, 2018 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfiechowski/f19a979848392b0a57e014cbc5fdc1a1 to your computer and use it in GitHub Desktop.
Save tfiechowski/f19a979848392b0a57e014cbc5fdc1a1 to your computer and use it in GitHub Desktop.
Cache child component state
class Child extends Component {
state = this.props.cachedState
? this.props.cachedState
: {
value: 0,
};
componentWillUnmount() {
if (this.props.saveState) {
this.props.saveState(this.state);
}
}
render() {
return (
<div>
<div>Value: {this.state.value}</div>
<button onClick={this.increaseValue}>Increse value</button>
</div>
);
}
increaseValue() {
this.setState({ value: this.state.value + 1 });
}
}
class Parent extends Component {
childrenStateCache = {};
render() {
return (
<Parent
cachedState={this.childrenStateCache['firstChild']}
saveState={state => this.cacheChildState('firstChild', state)}
/>
);
}
cacheChildState = (type, state) => {
this.childrenStateCache[type] = state;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment