DEV Community

talent
talent

Posted on

1

React Tip

๐Ÿ’ก React Tip๐Ÿ’ก

If you have a parent component which stores an array in the state like this:

๐˜ค๐˜ฐ๐˜ฏ๐˜ด๐˜ต ๐˜—๐˜ข๐˜ณ๐˜ฆ๐˜ฏ๐˜ต = () => {
๐˜ค๐˜ฐ๐˜ฏ๐˜ด๐˜ต [๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด, ๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด] = ๐˜ถ๐˜ด๐˜ฆ๐˜š๐˜ต๐˜ข๐˜ต๐˜ฆ([]);
๐˜ณ๐˜ฆ๐˜ต๐˜ถ๐˜ณ๐˜ฏ <๐˜Š๐˜ฉ๐˜ช๐˜ญ๐˜ฅ ๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด={๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด} ๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด={๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด} />;
}

And for some reason If you are adding new element to the array from the child component like this:

๐˜ค๐˜ฐ๐˜ฏ๐˜ด๐˜ต ๐˜Š๐˜ฉ๐˜ช๐˜ญ๐˜ฅ = ({ ๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด, ๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด }) => {
๐˜ค๐˜ฐ๐˜ฏ๐˜ด๐˜ต ๐˜ฉ๐˜ข๐˜ฏ๐˜ฅ๐˜ญ๐˜ฆ๐˜ˆ๐˜ฅ๐˜ฅ = (๐˜ถ๐˜ด๐˜ฆ๐˜ณ) => {
๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด([...๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด, ๐˜ถ๐˜ด๐˜ฆ๐˜ณ]);
};
// ๐˜ด๐˜ฐ๐˜ฎ๐˜ฆ ๐˜‘๐˜š๐˜Ÿ
};

then instead of passing the extra ๐˜‚๐˜€๐—ฒ๐—ฟ๐˜€ prop just to append to the original array state as shown below:

<๐˜Š๐˜ฉ๐˜ช๐˜ญ๐˜ฅ ๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด={๐˜ถ๐˜ด๐˜ฆ๐˜ณ๐˜ด} ๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด={๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด} />

you can pass only the ๐˜€๐—ฒ๐˜๐—จ๐˜€๐—ฒ๐—ฟ๐˜€ as prop to the child component and use the updater syntax of state for adding new user like this:

๐˜ค๐˜ฐ๐˜ฏ๐˜ด๐˜ต ๐˜Š๐˜ฉ๐˜ช๐˜ญ๐˜ฅ = ({ ๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด }) => {
๐˜ค๐˜ฐ๐˜ฏ๐˜ด๐˜ต ๐˜ฉ๐˜ข๐˜ฏ๐˜ฅ๐˜ญ๐˜ฆ๐˜ˆ๐˜ฅ๐˜ฅ = (๐˜ถ๐˜ด๐˜ฆ๐˜ณ) => {
๐˜ด๐˜ฆ๐˜ต๐˜œ๐˜ด๐˜ฆ๐˜ณ๐˜ด((๐˜ฑ๐˜ณ๐˜ฆ๐˜ท) => [...๐˜ฑ๐˜ณ๐˜ฆ๐˜ท, ๐˜ถ๐˜ด๐˜ฆ๐˜ณ]);
};
}

Here, the ๐—ฝ๐—ฟ๐—ฒ๐˜ƒ parameter will automatically receive the previous value of users array so you can easily add new element to it.

This will avoid the need of passing extra users prop.

๐—˜๐˜…๐˜๐—ฟ๐—ฎ ๐—ง๐—ถ๐—ฝ: In ๐˜‚๐˜€๐—ฒ๐—˜๐—ณ๐—ณ๐—ฒ๐—ฐ๐˜ hook, always try to use the updater syntax using the previous value as shown above so you don't need to add extra variable to dependencies array.

javascript #reactjs

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

๐Ÿ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay