I am unsure as to whether I should change my approach on how I render the components. I depend on a lot of modals that causes unnecessary re-renders when showing/hiding the modals.
This is a basic idea of how my components are currently being rendered:

I have cases where I can re-use the components (such as Component X in Component C and D), however there are cases (Component A3/B3 and Component E3) where the structure is completely different making it difficult to reuse the component. The problem I am encountering is slow UI due to multiple re-renders.
I display the modals based on state variables declared in their corresponding parent component. When changing the parent's state variable to display the modal causes the parent to re-render, and thus all of its children too. So as an example if I want to display the Create/Edit modal in Component A1, this will cause Component A, A2 and A3 to also re-render which is quite unnecessary. I have made use of the useMemo and useCallback hooks (https://reactjs.org/docs/hooks-reference.html#usememo) to help reduce the load, but I am unsure if this is the right approach? It feels like I am depending too much on the useMemo and useCallback hooks just to display a modal.
The idea behind the modals is to delete/edit/create a record that will display in the table (located in a different component). This is by design and I cannot change this.
To manipulate the data I am passing a callback function to each modal component. The modal component sends through the data being changed in the modal to the callback function where the data can be manipulated on the parent component.
CodePudding user response:
This is a case for React.memo. It is like the useMemo hook, but for components, and prevents re-renders of the component unless its props change:
const MyComponent = React.memo(function MyComponent(props) { /* render using props */ });If your component renders the same result given the same props, you can wrap it in a call to
React.memofor a performance boost in some cases by memoizing the result. This means that React will skip rendering the component, and reuse the last rendered result.
If this doesn't solve the issue because your modals and components share the same props, then it's probably time to reconsider the structure of your state so that you can separate it according to the concerns in your application.
Alternate approaches for independent use of "global" state include the context API, and various atomic state libraries like recoil and effector.
