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);
MyComponent
is a regular function with parametersprops
&context
.MyComponent
haspropTypes
as a static property.MyComponent
itself isexport
- this is so we can test it withoutpure
.- The default export should be a
pure
orconnect
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.
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.