💡 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)
For further actions, you may consider blocking this person and/orreporting abuse