Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

talent
talent

Posted on

     

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Tech Enthusiast | Problem-solver | People Connector | Relationship-builder | Cybersecurity Shinobi |
  • Location
    Cape Town,South Africa
  • Education
    UNIVERSITY OF SOUTH AFRICA (UNISA)
  • Joined

More fromtalent

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp