Skip to content

Instantly share code, notes, and snippets.

// Bad Example
export class ReferenceLiteralComponent extends React.Component {
doSomething() {}
render() {
return (
<View style={{ backgroundColor: 'red' }}>{
[1, 2, 3].map(
num => <Text onPress={() => this.doSomething()}>{num}: {new Date()}</Text>
// Epic used by both examples.
// Error handling etc. omitted for simplicity
export const profileEpic = action => action.pipe(
ofType(SEARCH_PROFILE),
switchMap(term => getProfileByTerm(term).pipe(
map(({ body }) => new SearchProfileSuccessAction(body)),
),
);
// Example
// Error handling and such omitted for simplicity
export const profileEpic = action => action.pipe(
ofType(SEARCH_PROFILE),
switchMap(term => getProfileByTerm(term).pipe(
map(({ body }) => {
let name = body.name;
if (name && name !== 'Andrew') {
name = name.toUpperCase();
/**
* Handling of time, network requests, and asynchronous
* logic more generally cannot be done by reducers.
*/
export const profileEpic = action => action.pipe(
ofType(SEARCH_PROFILE),
// Only allow one search every 300ms
debounceTime(300),
// Example
export const profileReducer = function (state = { name: '' }, { type, payload }) {
switch (action) {
case CHANGE_NAME:
return { ...state, name: payload };
default:
return state;
}
}
// Example
export const profileReducer = function (state = { name: '' }, action) {
switch (action.type) {
case CHANGE_NAME:
return { ...state, name: action.payload };
default:
return state;
}
}
// Example
export class RenderMethodComponent extends React.Component {
renderList = () => (
<View>{this.props.items.map(() => (
<Deeply><Nested><Views>
</Views></Nested></Deeply>
)}</View>
);
// Bad Example
export class EndlessComponent extends React.Component<{ animate: boolean }, { animate: boolean }> {
componentDidUpdate() {
const animate = { this.props };
// This will trigger `componentDidUpdate` in an endless loop
// even if the value of `animate` does not change.
this.setState({ animate });
if (animate) {
doAnimate();
import * as React from 'react';
import { Subscription, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
export class SetupTearDownComponent extends React.Component {
// If component doesn't mount but is town down, create an empty
// subscription we can call `.unsubscribe` on
networkSubscription = new Subscription();
// Alternatively you can have one subject that you emit with and use
// Example
export class ConstructorComponent extends React.Component<{ start: number }, { count: number }> {
// React Components takes `props` as a constructor argument. You can set default state here as well.
constructor(props) {
super(props);
this.state = { count: props.start };
this.count = countService.count();
this.positiveCount = this.count.pipe(filter(c => c > 0));
}