简体   繁体   中英

React avoid rerender of parent component when changing state from child component

I have this component:

const Parent = () => {
  const [a, setA] = useState({});

  return <Child setA={setA} />
}

const Child = ({ setA }) => {
  const [b, setB] = useState();
  const handleSomething = () => {
    setB({});
    setA({});
  }

  return b.map(etc => (...));
}

Basically, I want to avoid rerendering Parent component when a changes. Because this makes Child rerenders and it resets the internal state. How can I avoid it?

Ok so I was wrong, the rerender wasn't triggered because of the a or setA , it was because I was passing an object to Child like this

<Child filters={{someFilter, someOtherFilter}} setA={setA} />

To fix this I did this:

const filters = useMemo(() => ({ someFilter, someOtherFilter }), [someFilter, someOtherFilter])

<Child filters={filters} setA={setA} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM