'Component memoized with React.memo() keeps re-rendering
I have a ParentComponent
looking like this:
const ParentComponent = () => {
[product, setProduct] = useState({
name: "Test",
description: "Information goes here..."
})
return(
<ChildComponent product={product} updateProduct={setProduct}/>
);
}
and a ChildComponent
as follows:
const ChildComponent = ({product, updateProduct}) => {
// some code here
return(
<RichTextEditor content={product.description} update={updateProduct}/>
)
}
const isEqual = () => {
return true; // I want to force the component to never re-render
}
export default React.memo(ChildComponent, isEqual)
What's happening here is that I have a product
object with a description that is updated by the ChildComponent
. The value for the description gets set via updateProduct
every time the input changes in the RichTextEditor
component. I understand that because of the state change of product
the ChildComponent
gets re-rendered everytime which is unfortunate because that can cause unwanted effects like making the input field inside RichTextEditor
lose focus for example. So I tried forcing the ChildComponent
to never re-render with my isEqual
function that always returns true. It keeps re-rendering though, why is that?
I realize that there are other designs available to avoid this issue completely, and I'm probably going to do that anyways but before I do that I want to understand why I can not force ChildComponent
to not re-render.
Solution 1:[1]
If you are using useState
, useContext
or useReducer
then the component will still re-render.
This is straight from the docs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Radu Diță |