I have written following code:
function CreateModal({toggleCreatePorjectModal, fetchProjects}) {
const [formObj, setFormObj] = useState({name: "", link: "", error: ""})
function validateLinkAndCreateProject() {
if(formObj.link.trim() === "" || formObj.name.trim() === "") {
setFormObj(state => ({...state, error: "ALL fields are mandatory, please enter Project Name and Feed Link to create project."}))
return
}
rssFeedParser(formObj.link.trim())
.then((res) => {
axios.post(`${ServerPath}/projects/create`, {
name: formObj.name,
link: formObj.link
})
.then(response => {
if(response.data.error) {
setFormObj(state => ({...state, error: "Something went wrong. Please try again after some time."}))
} else {
fetchProjects()
toggleCreatePorjectModal(false)
}
})
.catch((err) => {
setFormObj(state => ({...state, error: err.msg}))
})
})
.catch((err) => {
setFormObj(state => ({...state, error: err.msg}))
})
}
return (
<div >
{/*Will Render Something based on above code*/}
</div>
)
}
I have used only one useState to store properties like "name", "link", "error" in one object. As I wanted to keep logic of FormObj and validateLinkAndCreateProject together. All three properties use only one useEffect. Hence, I thought that it is better to keep all three properties inside useState instead of creating 3 different usestate.
But my manager, and my technical architect telling me to create 3 useState, one useState for each property,that is, separate useState for name, link and error. According to them, never create object inside useState like useState({name: "", link: "", error: ""}). I should always create separate useState for each property.
As per my understanding, in older react we used to have only one state which use to have 30 to 40 properties in one object. With introduction of React hooks, as per "separation of concern", we are suppose to separate related logic from rest of the code. Hence, we will end up 5 to 6 states having objects with 4 to 5 properties.
Note: Here "separation of concerns" means breaking class code in such way that dependent state + useEffect + useRef etc kept together. below is quote from React documentation.
Hooks let you split one component into smaller functions based on what pieces are related (such as setting up a subscription or fetching data), rather than forcing a split based on lifecycle methods.
I wanted to Am I missing anything??, Is it okay to create useState({name: "", link: "", error: ""}). or should I create separate state for each one of them?