Skip to content

Instantly share code, notes, and snippets.

@developit
Created September 7, 2016 14:14
Show Gist options
  • Save developit/b3231344b6b056374bc630fa58308616 to your computer and use it in GitHub Desktop.
Save developit/b3231344b6b056374bc630fa58308616 to your computer and use it in GitHub Desktop.
pure-component for Preact

pure() can be used as a higher order function or a decorator.

When passed a pure functional component, it wraps the function in a classful Component with a shouldComponentUpdate() that ignores renders for unchanged props.

When passed a classful Component, it injects a shouldComponentUpdate() method into the Component's prototype that ignores renders for unchanged props & state.

Functional Example

import pure from 'pure-component';

export default pure( props => (
  <div>{props.foo}</div>
));

Classful Examples

Using it as a decorator:

import pure from 'pure-component';

@pure
export class Foo extends Component {
  render({ text }) {
    return <div>{text}</div>
  }
}

... or as a higher order function:

import pure from 'pure-component';

class Foo extends Component {
  render({ text }) {
    return <div>{text}</div>
  }
}
export default pure(Foo);
import { Component } from 'preact';
export default function pure(target) {
if (target.prototype && target.prototype.render) {
target.prototype.shouldComponentUpdate = shouldComponentUpdate;
}
else {
return target.__scuWrap || (target.__scuWrap = wrap(target));
}
}
function wrap(fn) {
class Wrap extends Wrapper {}
Wrap.prototype.renderChild = fn;
return Wrap;
}
class Wrapper extends Component {
shouldComponentUpdate(props) {
return shallowDiffers(props, this.props);
}
render(props, state, context) {
return this.renderChild(props, context);
}
}
export function shouldComponentUpdate(props, state) {
return shallowDiffers(props, this.props) || shallowDiffers(state, this.state);
}
function shallowDiffers(a, b) {
for (let key in a) if (a[key]!==b[key]) return true;
for (let key in b) if (!(key in a)) return true;
return false;
}
@FallingSnow
Copy link

Is this still relevant in preact? (Is there now an optimization in preact that makes this obsolete?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment