4

As I started learning React, I found the allure of declarative style of programming appealing. I try to avoid maintaining multiple state variables for data that can be derived from the base state itself that's stored in the redux store. It works wonders when I have to change something; as I just need to make changes to one function in the utils folder and that change is implemented across the whole app, rather than change the instances everywhere as was the case when I initially started working on this project after the previous dev left.

But I see myself redefining a lot of computed values everywhere, and if I just try to define them in the root component, I'll end up with a huge list of props being passed to a couple of components. Shifting it to the utils folder helps a bit, but then I find myself defining even the simplest of array filtering methods to the utils folder.

Is this need to define computed values everywhere a trade-off that you need to accept when you write declarative code, or is there a workaround/solution I am missing? As of now, the code-base is much better than how it used to be when they had a literal Java dev work on React with their knowledge of Java patterns being used in a framework that is the polar opposite of OOP, but I still feel like there's room for improvement in this duplication of computed values.

Comments
  • 0
    Hi,
    you said you're using redux for state management. Have you tried using selectors?
    redux.js.org/recipes/computing-derived-data

    Also, if you are using a newer version of react which supports hooks in functional components you could consider writing reusable hooks to retrieve computed values from state.
  • 1
    No, that’s not a trade off when using declarative style. I think that you have a misconception about a few things. There is no such thing as the opposite of OOP. Declarative and reactive style can live together with OOP. They key is to find a good separation of concerns and a good architecture for your data flow. There are no silver bullets here. Every project has different requirements and the architecture should be tailor made for that project. That doesn’t mean that you can’t use one of the "standard" architectures like MVC, though. You can. But any architecture can be achieved in different ways. For example OOP only or heavily reactive, or both.
Add Comment