Answer the question
In order to leave comments, you need to log in
How to prevent re-rendering of a component whose state changes in another child component?
Hello everyone, I have a component MainPage
, there is also a component Card
, a state and a function for changing the state Card
is located in MainPage
. When you change the state on a click, Card
a re-render occurs MainPage
. I would like to know how you can prevent the rendering of a component MainPage
or other components nested in it. . I know that useCallback and React.memo will help here, but I don’t understand exactly how to apply them. For convenience, I uploaded the project to codesanbox - https://codesandbox.io/s/trusting-williams-7yxpb?f... , because of which you can see what is being rendered in the console.
Answer the question
In order to leave comments, you need to log in
remove this useState from MainPage
since this data changes in one component, and is read in another (adjacent), then it is most canonical to move them to the store, for example, to redux, since it is here.
useCallback and React.memo are also needed. It makes sense to memoize Table, it is very bold. Accordingly, to create sortData, one cannot do without useCallback.
there are other jokes too. For example, sortUpData and other helpers. The array is mutably sorted. Yes, yes, arr.sort(...) returns the same array object, pre-sorted. This can cause rerenders to be lost on state changes. For immutability, it is necessary like this: arr.slice().sort(...) - a copy is created here and sorted.
I didn’t look at the rest, but I won’t be surprised if there is still some heresy on the ground ..
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question