React best practices.
Stateless components usually look like this:
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);MyComponentis a regular function with parametersprops&context.MyComponenthaspropTypesas a static property.MyComponentitself isexport- this is so we can test it withoutpure.- The default export should be a
pureorconnectwrapped 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.
It's probably the easiest way to write tests.
import React from 'react';
const Text = ({ text }, { doStuff }) =>
<div>{doStuff(text)}</div>;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 };// @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.