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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay