Delete the effect that copies props into state
Compute a filtered list during render so it follows the current props without an effect or a second state update.
You have a list component that takes a query prop. To show the matching items you keep a visible array in state and fill it from an effect. The first render after a query change still uses the old list. Computing the list during render keeps it in step with the current props.
import { useEffect, useState } from 'react'
export function FruitList({ items, query }) {
const [visible, setVisible] = useState(items)
useEffect(() => {
setVisible(items.filter((item) => item.includes(query)))
}, [items, query])
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
)
}To compare the versions, mount each with ['apple', 'banana', 'blueberry', 'pear'] and query="", then change the query to "b". Keep the array reference the same across the two renders that set props.
React commits the new query with the old visible state. The effect calls setVisible, which schedules a second render with the filtered list.
Compute it during render
visible depends on items and query. Compute it during render from those two props.
export function FruitList({ items, query }) {
const visible = items.filter((item) => item.includes(query))
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
)
}list effect: {"mount":2,"change":2,"shown":"banana,blueberry"}
list render: {"mount":1,"change":1,"shown":"banana,blueberry"}The first line is the effect version and the second is the render-time version. The render-time version renders once on mount and once on change, with the same two items shown.
The same approach works for a single derived value, such as const label = name.trim().toUpperCase().
When to reach for useMemo
A filter over four items is cheap, so I leave it bare. If the work is slow, wrap it in useMemo with the same inputs: useMemo(() => items.filter((item) => item.includes(query)), [items, query]).
useMemo pays off when something unrelated re-renders the component. In a test with a click counter in the same component, the plain version ran the filter 3 times across mount and two clicks. The memoized version ran it once.
Before adding it, measure. The memo costs a dependency array to keep correct, and for a small list that is more code than the work it saves.
The counts above come from a render without Strict Mode. For a development comparison, use the same root configuration for both versions because Strict Mode adds render and effect checks.