Skip to content

Instantly share code, notes, and snippets.

@timarney
timarney / coordinating-async-react.md
Created September 19, 2017 12:07 — forked from acdlite/coordinating-async-react.md
Demo: Coordinating async React with non-React views

Demo: Coordinating async React with non-React views

tl;dr I built a demo illustrating what it might look like to add async rendering to Facebook's commenting interface, while ensuring it appears on the screen simultaneous to the server-rendered story.

A key benefit of async rendering is that large updates don't block the main thread; instead, the work is spread out and performed during idle periods using cooperative scheduling.

But once you make something async, you introduce the possibility that things may appear on the screen at separate times. Especially when you're dealing with multiple UI frameworks, as is often the case at Facebook.

How do we solve this with React?

class Counter extends Component {
componentWillMount() {
let self = this;
class IfEven extends Component {
render() {
let {children} = this.props;
return !(self.props.value % 2) ? children : null;
}
}

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

Performance Conditionally Rendered Content in React

Some react components conditionally render content. When React first went public, a lot of us coming from handlebars really wanted "if" syntax. This gist isn't just about If components though, it's about any component that has an API that conditionally renders stuff.

{{#if stuff}}
//note:offset & speed could be setup as globals
/**
on page load or ajax update:
if(window.location.hash) {
// Fragment exists
scroll(window.location.hash,100,500);
}
direct: