Skip to content

Instantly share code, notes, and snippets.

@smith
Last active August 31, 2017 18:19
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 smith/dfe913dce779b3a65bc226ea97d4254c to your computer and use it in GitHub Desktop.
Save smith/dfe913dce779b3a65bc226ea97d4254c to your computer and use it in GitHub Desktop.
Caching HOC?
import React, { Component } from 'react'
import cacheComponent from './cacheComponent'
class AComponent extends Component {
onClick = () => {
this.props.set({ clicked: true });
}
render() {
return <div>Have I been clicked? {this.props.cache.clicked ? "yes :)" : "no :("} <button onClick={this.onClick}>click me</button></div>;
}
}
export default cacheComponent(AComponent);
export default {};
import appState from './appState'
import React, { Component } from 'react'
export default function cacheComponent(WrappedComponent) {
return class CacheComponent extends Component {
constructor(props) {
super(props);
this.state = appState;
}
set = (newState) => {
this.setState(newState);
}
render() {
return <WrappedComponent cache={this.state} set={this.set} {...this.props} />;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment