Search code examples
javascriptreactjsreact-hooksrenderreact-memo

I use React hooks and React memo to prevent my functional component from re-rendering ,but not work?


I use React.memo to control re-render, but my component still re-rendered. my code like this:

in my Template Component:

const Template = (props: Props) => {
  const { propsValue, data } = props
  const [value, setValue] = useState(propsValue)

  const handleChange = (value) => {
    setValue(value)
    props.onChange(value)
  }
  
  return (
    <div>
      {info.type === 'input' && <Input value={value} onChange={(event, val) => handleChange(val) onBlur={(event) => handleBlur()} />
      {info.type === 'image' && <Uploader multiple value={value} uploadUrl={data.uploadUrl} onChange={(val) => handleChange(val)} />
      {info.type === 'select' && <Select onChange={(val) => handleChange(val)} />
    </div>
  )
}

const areEqual = (prevProps, nextProps) => {
  if (JSON.stringify(prevProps) !== JSON.stringify(nextProps)) {
    return false
  }
  return true
}

export default React.memo(EditTemplate, areEqual)

in my Uploader Component:

const Uploader = props => {
  const [value, setValue] = useState(props.value)
  let { uploadUrl, multiple } = props

  const handleChange = ({ file, fileList }) => {
    if (file.status === 'done') {
      setValue(fileList)
      props.onChange(fileList)
    } else {
      setValue(fileList)
    }
  }

  return (
     <div>
       <Upload fileList={value} multiple={multiple} action={uploadUrl} onChange={handleChange} />
     </div>
  )
}

const areEqual = (prevProps, nextProps) => {
  if (JSON.stringify(prevProps) !== JSON.stringify(nextProps)) {
    return false
  }
  return true
}

export default React.memo(Uploader, areEqual)

when I change value in Select Component, the areEqual seems like not work, the address of all images in Upload Component will reload. why...?

the performance like this:

enter image description here

how can I do?


Solution

  • You're passing the onChange param to Uploader like onChange={(val) => handleChange(val)} so this effectively creates new function on each render and probably React.memo gives false positive because of this. Also in Uploader you have props.onChange(fileList) and fileList might also be the reason if it's a different Array instance everytime.

    In addition to @Ramesh Reddy's answer, you're calling setValue upon Select changes too, that could also be the reason, since you're using the new value as prop to Uploader.

    If this is not the reason, you can add a codesandbox sample with reproduction of the issue.