Skip to content

Latest commit

 

History

History
94 lines (60 loc) · 1.96 KB

React.md

File metadata and controls

94 lines (60 loc) · 1.96 KB

React

React best practices.

WARNING: outdated, needs love


  1. Stateless Components
  2. Type Checking

Stateless Components

1.1 Prefer stateless components

Stateless components usually look like this:

✓ GOOD

import React, { PropTypes } from 'react';
import { pure } from 'recompose';

import SomeComponent from '../SomeComponent/SomeComponent';

export const MyComponent = (props, context) =>
  <SomeComponent someProp={props.someProp}>
    {props.text}
  </SomeComponent>

MyComponent.propTypes = {
  text     : PropTypes.string.isRequired,
  someProp : SomeComponent.propTypes.someProp, // Here we can just reference instead of duplicate
};

export default pure(MyComponent);
  • MyComponent is a regular function with parameters props & context.
  • MyComponent has propTypes as a static property.
  • MyComponent itself is export - this is so we can test it without pure.
  • The default export should be a pure or connect wrapped component.
    • This ensures performance by preventing re-renders when props don't change.
    • Thus, the only way to re-render something is to change its props.

Type checking

2.1 Always check your props

It's probably the easiest way to write tests.

✘ BAD

import React from 'react';

const Text = ({ text }, { doStuff }) =>
  <div>{doStuff(text)}</div>;

✓ GOOD

import React, { PropTypes } from 'react';

const Text = ({ text }, { doStuff }) =>
  <div>{doStuff(text)}</div>

Text.propTypes = { text: PropTypes.string.isRequired };
Text.contextTypes = { doStuff: PropTypes.func.isRequired };

✓ BEST

// @flow
import React from 'react';

type Props = { text: string };
type Context = { doStuff: (text: string) => string };

const Text = ({ text }: Props, { doStuff }: Context) =>
  <div>{doStuff(text)}</div>

It's not necessary to specify propTypes when Flow Types are used.