Hello everyone i have a qeustion about good practices, it is fine to initialize state with map in condition like this?:
const [items, setItems] = useState(
someArray ? someArray .map(item => ({ ...item, isActive: false })) : [],
);
Yes it's ok to do, but there is an improvement that you should add. At the moment, your mapping operation is going to occur on each rerender of your function if someArray
is truthy. useState()
will ignore anything its passed after the first initial render, so those additional .map()
operations are wasted. To avoid doing those, you can pass a state initializer function into useState()
which only runs on the initial render, avoiding all the unnecessary calls to .map()
for any future rerenders of your component:
const [items, setItems] = useState(() =>
someArray ? someArray.map(item => ({ ...item, isActive: false })) : [],
);
You should also be aware that useState()
only uses the value it's passed on the first render, so if someArray
changes in subsequent rerenders, your items
will not change as it will still hold the array it was initially passed when your component was first initialised. To change items
, you would need to call setItems()
instead. Alternatively, you may not need to use state at all if items
needs to update on each render as someArray
change and instead create a regular variable that you assign the result of calling .map()
, which you can make more efficient by using useMemo()
.
Lastly, I would also consider using Array.isArray()
as your ternary condition, as not all truthy values have a .map()
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.