DEV Community

Discussion on: 3 Tips to write better react components

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

You didn't mention it in this article, so I gotta ask: Were you previously using Redux before using Hooks/useState? I'm asking because I've seen other articles (here and on other sites) with a similar message about useReducer(). They show some functional logic with useState(), they mention how "ugly" the code looks, then they refactor it to use useReducer() and they seem to be quite satisfied with the (supposedly) new-and-improved look.

This comment isn't meant to be "anti"-useReducer(). useReducer() is a tool. If you're more comfortable using that tool, then great! But for the life of me, I can't look at the difference in those two examples (or in others I've seen) and fathom why the useState() example is "bad" or the useReducer() example is "good".

Whether it's stated in the narrative or not, I usually find that the implication in these articles comes down to: "I'm accustomed to using Redux. And that's why I think that the code looks so much better with useReducer()."

If this isn't true for you, then I apologize for the presumption. Even if it is true for you, this isn't meant as a critique on your article or your examples. You did a fine job. I'm just honestly trying to find out whether people who aren't already familiar with Redux are truly seeing useReducer() as such a "better" or "cleaner" alternative to useState(). Or... (as I suspect), the former Redux users are the ones that are more enamored with the useReducer() approach.

Collapse
 
elisealcala profile image
Elizabeth Alcalá

Hi, I don't know if it looks like but I'm not familiar with Redux, I think I used it just two times in my two years working as a developer.

I know what you mean when you said that you can't look at the difference in those examples, but I didn't mean that useState code just look ugly and useReducer is better, it's just that for this component, in particular, having multiple setState just didn't work. It's not maintainable.

And this doesn't mean that I'm going to use useReducer for all my components. I'm using useState 90% of the time, and that will not change, but when you have a complicated state, you may need a reducer.
Adding actions can increase your vision of what's happening with all your states. But also you can have a very clean and readable code with just using setState.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

Ahh, very interesting. Thank you for the reply (and I agree with you).