๐ก 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.
Top comments (0)