DEV Community

Discussion on: I replaced useState hook with custom one

Collapse
 
abdelrahmanahmed profile image
Wahdan • Edited

Question from my side, why you are not using something like that :

let [state, setState] = useState({
    name: "",
    email: "",
    phone: "",
})
Enter fullscreen mode Exit fullscreen mode

and whenever yo want to update the state, for example lets update the name field :

setState(
...state,
{
name:"wahdan"
})
Enter fullscreen mode Exit fullscreen mode

even with const it will behave the same

Collapse
 
filippofilip95 profile image
FilippoFilip • Edited

Hi, thanks for your comment :) Your code solves the same problem as I'm describing in article, only without using custom hook.

I would definitely also use your implementation but still:

  • Direct destructing of previous state in setState function could happen to be repeated in many event handlers in your component. So you will need to type ...state for many times in one component.
  • Extracting that "object merging" to separate custom hook could maybe in shortest possible way look like:
function useSetState(initialValue) {
    const [state, setState] = useState(initialValue);

    return [state, (newState) => setState({
        ...state, ...newState,
    })];
}
Enter fullscreen mode Exit fullscreen mode

and than to be used like:

setState({ name: "John" }
Enter fullscreen mode Exit fullscreen mode

If you import this hook into many of your components, than this way still gives you option to avoid destructing of previous state like ...state as i mentioned above.

  • Becouse of that it just worth it to have it as custom hook :D
Collapse
 
munawwar profile image
Munawwar

Yea.. aside from it not looking nice to always repeat the same thing, there is the issue of forgetting to spread when doing the setState .. and that results in overriding the entire object and other bugs.