<div id="app"></div>
function FooComp (props) {
  console.log("Foo render", props.name)
  return <div onClick={props.onClick}>Foo {props.name}</div>
}

const Foo = React.memo(FooComp)

function App () {
  const [checked, setChecked] = React.useState(false)
  const list = ['a', 'b', 'c', 'd']
  const cache = React.useRef({})
  
  // function handleClick () {
  //   console.log('clicked')
  // }
  
  const handleClick = React.useCallback((index) => {
    console.log('clicked', index)
  }, [])
  
  return (
    <div>
      <label>
        <input
          onChange={event => setChecked(event.target.checked)}
          type="checkbox"
          checked={checked}
          />
        点击切换
      </label>
      {list.map((item, index) => (
        <Foo
          key={item}
          name={item}
          onClick={cache.current[index] || (cache.current[index] = () => handleClick(index))}
        />
      ))}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'))
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js
  3. https://cdn.jsdelivr.net/npm/sweet-log/dist/index.js?display=1