Created
April 6, 2018 09:18
-
-
Save tfiechowski/f19a979848392b0a57e014cbc5fdc1a1 to your computer and use it in GitHub Desktop.
Cache child component state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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