React state management for forms (creation is simple but reusing for editing is hard)
I am constantly building forms for creation and editing of different entities in my web app (like tasks, notes, contacts, etc.). However, I wanted to understand what is the recommended way of managing state of these forms in a way that -
1. Reuses components
2. Is performant
Let's take the example of task creation and editing modal. What I currently do -
Create a context around the task modal that takes in an optional task prop. If the task prop is not provided, I set the useState values to default values of a new task and if a task is provided, then I set the task's values for the initial useState values. For each of the components of the modal, like task name, task due date, etc. I get the values for those elements from the context and update them in the context (this has an issue that if one component is being updated, it re-renders all the other components since they all use the context). This structure takes care of being able to re-use the components for create and edit.
Then based on whether the modal is being used for create or edit, I call a createTask or updateTask function from the context in the modal.
Does this structure make sense or is there a better way to handle creation and editing of entities in the same modal?
1 Reply
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View