Help us understand the problem. What is going on with this article?

jsx-no-lambda を recompose で回避

More than 1 year has passed since last update.

背景

tslint などには jsx-no-lambda というルールがある。
これは、 React の render 内で lambda 関数を作成すると、処理によってはメモリを消費して重くなるため、良くないとされているため。

// NG
const Component = ({ onChange }) => (
  <input onChange={e => onChange(e.target.value)} />
)

export default Component

回避方法

Lint を黙らせるだけなら

// 回避できてない?
const Component = ({ onChange }) => {
  const _onChange = e => onChange(e.target.value)

  return <input onChange={_onChange} />
}

export default Component

で良いが、 re-render の度に関数を作成している点では同じでは?と思ってしまう。

recompose を使って回避

TypeScript の型定義など含めると、記述量が多くなってしまうが、 recompose を使って回避するのが良いかなと思った。

import { withHandlers } from 'recompose'

const Component = ({ _onChange }: Props) => (
  <input onChange={_onChange} />
)

export default withHandlers({
  _onChange: ({ onChange }) => e => onChange(e.target.value),
})(Component)

一度定義した関数 ( _onChange ) を使いまわしているので、何回 render してもメモリ消費量は増えない・・・はず?

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away