1

I have a form with a lot of fields and some attachments. I'm using the React hook useState to set form data. In React, I'm not supposed to mutate the state directly so when an input fires a change event, I need to make a copy of the object and then use setState.

I notice that setState is SLOW when my state object is big and nested. Especially when the state object contains attachments, copying the object like below will also copy all the bytes in attachments. That can make the page very slow and unresponsive.

Hook:

 const [requestViewModel, setRequestViewModel] = useState<RequestViewModel>({
            id: 0,
            contacts: [] as UserRequestRole[],   
            attachments: [] as RequestAttachment[],
            ..other fields
        });

This is slow:

 setRequestViewModel({ ...requestViewModel, [name]: value });

How to copy objects with less overhead?

John Smith
  • 29
  • 3

1 Answers1

0

Yes, it's gonna be slow. Here's a good summary of the issue: https://stackoverflow.com/a/57102754/7082724

You may want to flatten / simplify your state, or use multiple useState calls, or you may want to switch to using useReducer.

Kevin Ashworth
  • 602
  • 6
  • 11