Skip to content

Instantly share code, notes, and snippets.

View developit's full-sized avatar
🦊
write, the codes

Jason Miller developit

🦊
write, the codes
View GitHub Profile
@developit
developit / purecomponent.js
Created April 25, 2017 11:43
PureComponent for preact
import { Component } from 'preact';
export default class PureComponent extends Component {
shouldComponentUpdate(props, state) {
return !(shallowEqual(props, this.props) && shallowEqual(state, this.state));
}
}
function shallowEqual(a, b) {
for (let key in a) if (a[key]!==b[key]) return false;
export class Demo extends Component {
state = {
show: false
};
toggle = () => {
this.setState({ show: !this.state.show });
};
render({ }, { show }) {
class PureComponent extends Component {
shouldComponentUpdate(props, state) {
return shallowEqual(props, this.props) && shallowEqual(state, this.state);
}
}
function shallowEqual(a, b) {
for (let key in a) if (a[key]!==b[key]) return false;
for (let key in b) if (!(key in a)) return false;
return true;

tracked npm

@tracked is a decorator for Preact that makes working with state values no different than properties on your component instance.

It's one 300 byte function that creates a getter/setter alias into state/setState() for a given key, with an optional initial value. The "magic" here is simply that it works as a property decorator rather than a function, so it appears to integrate directly into the language.

tracked has no dependencies and works with any component implementation that uses this.state and this.setState().

Installation

let Components = require('./Components').default;
let Demo = () => (
<Router history={createHashHistory()}>
<Components path="/" />
{ require.context('./demos', true, /Demo$/).keys().map( file =>
<LazyComponent load={ cb => require.ensure(file, cb) } />
) }
</Router>
);
@developit
developit / .gitignore
Last active December 4, 2019 09:31
it's actually 3.9kb
.DS_Store
node_modules
dist
@developit
developit / factory-loader.md
Created March 25, 2017 18:24
factory-loader

Factory Loader

This is a tiny webpack loader that invokes a given module with another as an argument.

What's that useful for? Dependency Injection! Maybe this is how we can solve the VDOM fragmentation issue.

Example

Here's a library-agnostic VDOM component. Notice that it doesn't import react/preact/inferno/whatever - instead, it takes the VDOM library as an argument.

var preact = require('preact');
var createRenderer = require('./preact-dom-renderer');
// set up a rendering target
var renderer = createRenderer();
// render some stuff into the internal DOM
renderer.render(preact.h(PreactApp, pageConfig));
// get a snapshot of the current HTML
node_modules
@developit
developit / components.js
Created February 22, 2017 19:25
vdom agnostic components
import preact from 'preact';
import createFoo from './foo';
import createBar from './bar';
export const Foo = createFoo(preact);
export const Bar = createBar(preact);