I have two Components, and I wrapped Parent with React.memo
:
Child
const Child = ()=> <div>I'm Child</div>
export default Child
Parent
const Parent = (props)=> <div>{props.children}</div>
export default React.memo(Parent)
Use in App:
const App = () => {
const [count, setCount] = useState(0)
return(
<div>
<button onClick={()=>setCount(count+1)}></button>
<Parent>
<Child></Child>
</Parent>
</div>
)
}
Click the button, result:
The Parent Component will rerender, so the memo not working because it's children is a function component
So, how can I prevent rerender?
I know a way to solve by useMemo, but it's ugly and not friendly, do you have better ideas?
const App = () => {
const [count, setCount] = useState(0)
const children = useMemo(()=><Child></Child>,[])
return(
<div>
<button onClick={()=>setCount(count+1)}></button>
<Parent>
{children}
</Parent>
</div>
)
}
Child
component is rendered by theApp
component. So either you move the rendering ofChild
into theParent
component or you also wrapChild
inReact.memo()
. – ChloeParent
will still re-render because itschildren
prop technically changes whenApp
re-renders, which is why evenReact.memo()
doesn't help there. Basically the best way around that seems to be what you did usinguseMemo
. You have to memorize what you pass toParent
as children or it will re-render. – Chloe<Parent><Child1/><Child2><Granchild1></Grandchild1></Child2></Parent>
and so on, it goes deep many layers (my app is a bunch of mini components). How do I deal with this complexity? – Emilyemina