Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
67 lines (50 sloc) 3.12 KB

React.memo

React.memo, with memo for memoization, is used on functional components that are supposed to render the same result given the same props.

The signature of React.memo is as follows:

declare export function memo<Config, Instance = mixed>(
  component: React$AbstractComponent<Config, Instance>,
  equal?: (Config, Config) => boolean
): React$AbstractComponent<Config, Instance>

And we can use it this way:

// @flow
const React = require('react')

type Props = {| cornStyle: 'spiraling' | 'colorful' |}
function Unicorn(x: Props) {
  return null
}
const MemoUnicorn = React.memo<Props>(Unicorn)

const memo_unicorn_ok = <MemoUnicorn cornStyle="spiraling" /> // ok
const memo_unicorn_error = <MemoUnicorn corn="spiraling" /> // error

We may optionally provide an equal method as a performance optimization. memo provides the type information for the method with the same props type we supplied, and we don't need any extra type annotations for it. And since we did provide a Props type parameter to React.memo, Flow is able to catch errors on the equal method:

const memo_unicorn_with_equal_ok = 
      React.memo<Props>(Unicorn, (props1, props2) => props1.cornStyle === props2.cornStyle); // ok

const memo_unicorn_with_equal_error = 
      React.memo<Props>(Unicorn, (props1, props2) => props1.corn === props2.corn); // error

And we can pass the returns of React.forwardRef to memo:

const { useImperativeHandle } = React

function Demo(props, ref) {
  useImperativeHandle(ref, () => ({
    moo(x: string) {},
  }))
  return null
}

const Memo = React.memo(React.forwardRef(Demo))

function App() {
  // Error below: moo expects a string, given a number
  return <Memo ref={ref => ref && ref.moo(0)} />
}

References

You can’t perform that action at this time.