5 ms·
If you have a list of elements rendered in a container (from array), does React always re-render the whole thing (contents of container) when adding / removing
by journey_16162 5y ago
If you have a list of elements rendered in a container (from array), does React always re-render the whole thing (contents of container) when adding / removing elements from the array or is there a way to work around that? I'm coming from Svelte, I would not be learning React if it was not for its omni-presence in the job market and I'm genuinely curious.
- fabian2k 5y agoReact will nag you to give the array elements unique keys so that it can track them. If you do that, it will generally be able to avoid manipulating the DOM for those elements of the array that did not change. It will still render (= execute the JS of the component) all of them by default, how expensive that is depends entirely on the content of your components. If that is a problem you can use React.memo() to prevent rerendering of those components if their inputs did not change.
- wereHamster 5y agoWell, it's only efficient if the component which renders each element in the list gets a stable key AND is React.memo() AND the props passed to the components do not make the React.memo() pointless. For example the following will not be particularly efficient, because a fresh callback is passed to the component on each render. <> {array.map((data) => ( <SomeComponent data={data} onClick={() => { alert('nope'); }} /> )} </>
- fabian2k 5y agoThat's what useCallback is for. And it really depends on how heavy the child components are on whether all this makes a noticeable difference.
- brundolf 5y agoReact will iterate over the whole array again (the array causes the container component to re-render, and its contents including the JSX are just JS that gets run again), but the individual components rendered from the array can prevent their own internal render logic from being called again unnecessarily by using React.memo
- acemarke 5y agoYes. React re-renders components recursively by default. So, any state update in a parent component will recurse through and render all child components. But, a "render" does not necessarily imply a "DOM update" - it's about asking the components "what do you want the UI to look like now?", and determining _if_ updates are needed. This can be optimized if needed. For more details, see: - https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/ https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-... - https://www.zhenghao.io/posts/react-rerender https://www.zhenghao.io/posts/react-rerender