reactjstypescriptfront-end-optimization

Filter List to render or conditionally render list's elements


I want to render a list (or array) of objects but that rendering would be based on some boolean condition. What is the most optimized way to approach this:

const list: object[] = [....]  // Coming from somewhere else

const (renderList, setRenderList): object[] = []  // List that will be rendered

// option1
useEffect(() => {
    setRenderList(list.filter(...));  // On every change in list, filter the rendered list based on the condition
},[list])

renderList.map((el) =><RenderThis />);

// option2 
// no use of renderList
// filter each element of renderList and conditionally render it

list.map((el) => {
    if(el.something === condition) && <Render />
})

Solution

  • You definitely don't need useEffect here.

    If the boolean condition is cheap then go with option 2:

    list.map((item) => checkCondition(item) && <Item ... />)
    

    Otherwise use useMemo:

    const filteredList = useMemo(() => list.filter(checkCondition), [list]));
    

    If list hasn't changed react will use the previous value.