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

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More