Why I like to decouple my React views from my logic

  Рет қаралды 18,060

Web Dev Cody

Web Dev Cody

Күн бұрын

Пікірлер: 105
@abhinav.robinson
@abhinav.robinson 2 жыл бұрын
Sounds pretty interesting, I would love to see a series/video for building a app from scratch using these principles… good job 👏
@WebDevCody
@WebDevCody 2 жыл бұрын
Don’t actually use this approach, this was more of a thought experiment video to explain a concept to decouple your code. 🍻. Using redux, mobx, overmind.js would be my recommendation to achieve this same approach
@jvzaniolo
@jvzaniolo 2 жыл бұрын
What approach do you use instead then?
@thatdooddillon
@thatdooddillon 2 жыл бұрын
LOL
@WebDevCody
@WebDevCody 2 жыл бұрын
@@jvzaniolo I said in the video I use cerebraljs or overmindjs
@skl9942
@skl9942 2 жыл бұрын
Thats great, so now I know how to not do it, very helpful.
@WebDevCody
@WebDevCody 2 жыл бұрын
@@skl9942 the concept still remains and I’d say this approach is fine if you want to allow easier unit testing of components. I’d just use overmind.js since it does all the heavy lifting for us
@kevinandeleven
@kevinandeleven 2 жыл бұрын
A reason why I like Vue.. It makes decoupling business logic from vue specifics very easy in vue 3 with the composition api
@WebDevCody
@WebDevCody 2 жыл бұрын
Sure, but the composition api seems just like react hooks to me?
@kevinandeleven
@kevinandeleven 2 жыл бұрын
@@WebDevCody yes, the idea of composition api is related to react Hooks, but it allows a whole lot of freedom that hooks do not.. For example, the idea you were trying to implement that when the ToDo array changes, it calls the render fn, Vue ref which is equivalent to useState in react handles that beautifully with proxies so that you can use a ref in other contexts that don't include vue's traditional use of it
@johnobiofiong
@johnobiofiong 2 жыл бұрын
@@kevinandeleven I think i get what you mean...
@bitfluent
@bitfluent 2 жыл бұрын
Are there any performance disadvantages to this approach since you are forcing a complete re-render on every state change?
@WebDevCody
@WebDevCody 2 жыл бұрын
Sure, I bet there are, but I don’t think rerendering a page in react is as slow as everyone keeps saying it is. If you need speed don’t use react
@bitfluent
@bitfluent 2 жыл бұрын
@@WebDevCody I'm sure in smaller projects it's negligible. My concern was in regards to larger applications where preventing unnecessary re-renders is a priority. In this approach, while it does make the code more portable (and I love that btw), I'm hesitant to implement it if it means my entire app needs to re-render on every state change. Perhaps React and other frameworks have ways to address the issue that I'm unaware of (maybe dumping your isolated state into context, so state can be tracked? useMemo() is enough, maybe?)... Just theorizing for now.
@WebDevCody
@WebDevCody 2 жыл бұрын
@@bitfluent we do a similar approach in our app using the cerebral.js lib. I do think the entire component tree is rerendered on any state change, but we don’t notice any big issues. Our biggest slowdown is always due to http requests taking too long. When react gets the data it’s pretty quick to show it unless you are showing hundreds of components on a single page which is always a smell of bad UX)
@however1456
@however1456 2 жыл бұрын
What's the name of this Theme VS Code?
@sachinahya7502
@sachinahya7502 2 жыл бұрын
I think the overall concept is sound, and there are some good examples of libs like Testing Library where the core business logic is separate from the framework bindings. I think the main issue I have with it is the number of props you have to pass, so I'd personally still have some minimal framework coupling via custom hooks (e.g. useAddTodo) that do the binding but still abstract the controller away from the view.
@WebDevCody
@WebDevCody 2 жыл бұрын
Either passing props or a bunch of hooks, the functionality and state needs to come into the components somehow I’d say. I personally would rather it all come in as props since it’s easy to know exactly what a component needs
@Will4_U
@Will4_U 2 жыл бұрын
Found you by the react devtools tutorial - this is really great content! I'm a fan of concepts like separation of concerns and this approach looks really cool. I have to try it out.
@ThanHtutZaw3
@ThanHtutZaw3 2 жыл бұрын
Question: I make note app with next js and when I use dynamic route sometime chrome is covering back button of note app Sometime it doesn't cover. How can I fix it. Issue only in Chrome Mobile browser (between Fullscreen and Not Fullscreen)
@coldym
@coldym 2 жыл бұрын
Aren't custom hooks used to decouple logic from ui?
@WebDevCody
@WebDevCody 2 жыл бұрын
Sure, but I think the idea I was getting at was to decouple from react because your custom hook is probably filled with tons of useState and useEffect calls. I’ll admit this video is an extreme view on decoupling your ui presentation layer from the view engine and most projects do not need this, this was just an thought experiment
@yousafwazir3167
@yousafwazir3167 2 жыл бұрын
Is there another approach you cloud take for scalability ?
@WebDevCody
@WebDevCody 2 жыл бұрын
Scalability, meaning like how large your project gets?
@yousafwazir3167
@yousafwazir3167 2 жыл бұрын
@@WebDevCody yes
@returncode0000
@returncode0000 2 жыл бұрын
What do you think about nest.js? It also based on the MVC principle.
@WebDevCody
@WebDevCody 2 жыл бұрын
I have not used it yet
@returncode0000
@returncode0000 2 жыл бұрын
@@WebDevCody You may should take a look. Pretty interesting.
@WebDevCody
@WebDevCody 2 жыл бұрын
@@returncode0000 I’m not a fan of decorators everywhere with @ symbols. Seems like a code smell and going back to enterprise java
@returncode0000
@returncode0000 2 жыл бұрын
@@WebDevCody Exactly, thats were I come from (Java/Spring/Spring Boot). Maybe thats the reason why I like it but I understand your point.
@AustinMarlar
@AustinMarlar 2 жыл бұрын
Interesting approach. It feels like Angular almost. A major issue I see with this approach is that none of the views seem to be tested giving a false sense of security. Just because the controller tests are passing doesn't mean someone didn't screw up a view while editing/refactoring it and now a button doesn't work even though the tests pass. A great thing about testing-library is not needing to mock things and using the site as the user would which tests my view, controller, model, utils, kitchen sink, etc... The only thing I really mock are my API calls and I do that with MSW and it's super simple. The other thing I mock are dates but jest/vitest handle that for me. When a helper/util function is complex, I write additional tests for it.
@WebDevCody
@WebDevCody 2 жыл бұрын
Yeah that is the main downside. You have to first convince yourself that some things are ok to not test, or might be covered later using cypress. We don’t test our views. On our project we find that forgetting to call a click handler (or invoking it incorrectly) is not the thing that often breaks. It’s very easy in typescript to see if you’re calling a method correctly from your view. What often breaks is the complex logic under the hood which determines when something should display or not, or what actually happens when you click the button and state updates
@habong17359
@habong17359 2 жыл бұрын
This is a good point. But yeah, it depends on how the team works around testing. We handle testing the view on cypress(E2E) and keep unit tests scope to functions so this approach may work out. Interesting approach!
@appel-32
@appel-32 2 жыл бұрын
I kinda need some advice here. I'm on a personal project (next.js prisma tailwindcss), the thing is: i'm using next.js to render the frontend but also using it as rest api (/api endpoint). Should I turn around my code and work with tRPC or should i keep it this way. I don't expect the app to accept external requests to the api so i feel like having and endpoint is pointless (i need to protect it from users that aren't authenticated, etc etc). hope i make myself clear, English isn't my main language so I'm having a bit of a trouble explaining myself 😓
@WebDevCody
@WebDevCody 2 жыл бұрын
Either is fine. There is no issue with rest but if you’re already using typescript I’d give tRPc a try.
@iamnwanguma
@iamnwanguma 2 жыл бұрын
How would you use libraries like React Query in the controller
@avi7278
@avi7278 2 жыл бұрын
You can avoid the render call by setting up your controller as a render prop component, use useState (or any state library that exposes hook like jotai atoms) for state, useMemo for computeds with dependency array of your state ellements, and useCallback for actions, then wrap the render prop component/controller around your feature's view wrapper component that consumes all your dumb components. Admittedly your controller is not decoupled from React but it's a lot less likely that you're moving away from React itself than nextjs/remix/etc.
@WebDevCody
@WebDevCody 2 жыл бұрын
Interesting I’ll have to check this out. I don’t actually code react apps in this way since this was more of a though experiment, but it’s good to keep these things in mind as you plan to build larger apps with lots of tests and other developers
@avi7278
@avi7278 2 жыл бұрын
@@WebDevCody Yeah, well you're right about it. Before hooks, I was even more of a hard-liner on this approach, but imo hooks provide an ideal approach for managing and optimizing component re-renders so I find coupling controllers to React itself a viable tradeoff. That said, you could still have agnostic controllers and glue them to React with an additional layer similar to the approach described above, and these could be generated from the controllers themselves. You know, if you actually needed that sort of thing.
@elvarght
@elvarght 2 жыл бұрын
There's a reason why some dev praise TDD. Unit test are a critical part of an app. It makes your logic consistent and make it a lot easier to find why a test is failing because it test very little at a time so if that test breaks, it means that specific function doesn't work anymore.
@WebDevCody
@WebDevCody 2 жыл бұрын
I’m not seeing the connection between tdd and this video. I do think this approach can make components easier to unit test if you don’t care about actually simulating html dom events.
@d2vin
@d2vin 2 жыл бұрын
i finally know what decoupling means. a tutorial on overmind would be dope.
@ravindranathmajji
@ravindranathmajji 2 жыл бұрын
This is excellent, i liked it.
@faraonch
@faraonch 2 жыл бұрын
I am glad you mentioned it in the end. THIS is simply the purest way over-engineering. It adds technical debt for something we don't know yet for something that will not be the case for sure. Showing this on a Todolist example makes it even worse. Amateurs do not see it and take this as a "good" idea for their mini-app. If it was meant for demo only, the it must be show in that context. It will simply never be the case that you have to rewrite a big app from React to e.g Remix. The scope will be completely new, team will be new, it's easier and faster to write it on a greenfield from scratch. No Lead Developer ever would be glad to have this "abstraction".
@WebDevCody
@WebDevCody 2 жыл бұрын
Agreed
@uome2k7
@uome2k7 2 жыл бұрын
This makes things harder than they need to be. The actual problem is your component is doing too much. Split it up into more manageable pieces and then test those. All these extra flavors of react is also getting people in trouble. Instead of coupling to some flavor, learn what it does that makes you want to use it and then try using the same patterns. As for unit testing vs integration testing...it really depends on what you are doing. Even if you manage 100% coverage through unit tests, you need to test how those units are being used (integration tests)
@WebDevCody
@WebDevCody 2 жыл бұрын
Idk, it’s hard to unit test components in react without mocking and spying on everything imo, which is another smell. Although, I can agree this approach might be extra complexity.
@lord_vats
@lord_vats 2 жыл бұрын
This just made me realise that Angular is quite good.
@DeweyWaspada92
@DeweyWaspada92 2 жыл бұрын
I use similar approach in my work to test the business logic. I have a component that handles a quite complex user subscription flow: it handles anonymous users, asking for authentication, premium users, users who want to resubscribe, etc, looots of stuff. The react component (view) job is to observe data change from redux (like detecting a login) with useEffect but then delegates to `controller.authSuccessful` so the main logic is still in the controller. I use this technique only in places with critical AND complex logic, accompanied by the unit test to make me sleep good at night. I know it may not always work in the view but at least I know that when something doesn't work it's the glue code, NOT the core logic. Not a super fan of react testing library to test business logic for the same reason as you mentioned. Also because of the fact that it uses JSDOM under the hood 😄. Too cumbersome to test complex logic BEHIND a complex UI. We use Cypress anyway to cover common cases
@HisokaXKuroro1
@HisokaXKuroro1 2 жыл бұрын
for the same reason I think it's better to use css classes to reuse the style in case you change your framework/library
@WebDevCody
@WebDevCody 2 жыл бұрын
I could agree with that. A lot of this css-in-js seems like an huge increase in coupling. Tailwind and SaaS is less coupled since it just uses classes and those classes can always be applied to react, vue, svelte, etc.
@HisokaXKuroro1
@HisokaXKuroro1 2 жыл бұрын
@@WebDevCody finally a KZbinr who's not drived by hype 🎉
@WebDevCody
@WebDevCody 2 жыл бұрын
@@HisokaXKuroro1 I’d still be using Sass if everyone didn’t hype up tailwind, so idk about that haha. I am cautious about new tech and approaches before truly understanding their impacts of systems and maintainability.
@HisokaXKuroro1
@HisokaXKuroro1 2 жыл бұрын
@@WebDevCody indeed you need to stay up to date and sharp
@mysterio7385
@mysterio7385 2 жыл бұрын
@@WebDevCody do you mean SASS?
@yuraholomb4667
@yuraholomb4667 2 жыл бұрын
This is a really interesting appoach. But if our components should be so dumb, they would probably not use things like useEffect, useState etc. So maybe in that case React is not needed and can be replaced with some another library which would do more like template rendering on the FE side?
@WebDevCody
@WebDevCody 2 жыл бұрын
React is a view library, so it’s fine to use it for one. Most template library’s kind of suck, such as mustache, handlebars, etc compared to using react with jsx. Let’s be honest, no one writes react the way I did in the video, but it’s a good idea to think about the potential maintenance issues that might come up if you one day decide you no longer want to use next or react and instead want to use svelte because it renders faster or something.
@avi7278
@avi7278 2 жыл бұрын
That is correct if: 1) you'd like to use an inferior view library, 2) you also want to manually handle everything else React gives you, which isn't insignificant by any means.
@yuraholomb4667
@yuraholomb4667 2 жыл бұрын
@@WebDevCody Yeah, this approach have some potential as for me, and I think that the way we are writing the React apps right now need some kind of revolution which would lead to something similar you've showed us. Have you thought about creating own library for such decoupled logic?
@SeibertSwirl
@SeibertSwirl 2 жыл бұрын
Good job babe!
@Goyo_MGC
@Goyo_MGC 2 жыл бұрын
Always nice to hear about other point of you. I have to agree with you it does remind me of the good old MVC model. However i dont find it really comparable because in modern app you would usually have you backend completely separated from your front application. Where i find your approach specificaly interessing is with the case of Next.js. I'm starting to get tempated and get back to a one project for both backend and frontend and what kept me from doing so is the lack of specific speration with the controller. It would be interesting to see how you would organize your files on a Next project that render the front but also act as a REST API. Regards :)
@returncode0000
@returncode0000 2 жыл бұрын
The MVC concept is pretty important and in the java/spring world it's basicially the core concept. So, good point here, very good content from your side (as always) by picking it up and took this concept into the react/next world. Would like to hear more about it 👍
@Sky-yy
@Sky-yy 2 жыл бұрын
Awesome one 💯
@rand0mtv660
@rand0mtv660 2 жыл бұрын
I think this also heavily depends on the project. Not every React project is a big app that is continually being worked on. Some projects are developed and then just used with maybe super small bug fixes or tweaks down the line (6 months, 1 year etc.). Some projects are also not big enough to warrant all sorts of testing and abstractions, it's just not worth it. In my opinion, those projects don't benefit from testing that much and from this separation as well. It just adds developer overhead and cost. On the other hand, for a project that's being constantly worked on and by multiple people/teams, testing and this separation could bring a lot of security and benefits. Also, as someone mentioned in the comments just because a controller is passing tests doesn't mean that view is using that controller properly, but it's definitely harder to mess up in your UI if it's just calling controller logic. I'm not really much of an MVC guy, but I definitely do see benefits by doing some of this stuff.
@WebDevCody
@WebDevCody 2 жыл бұрын
yeah, and my perspective is from working on a team of 9 developers pushing code daily to a 4 year project, so our app has a lot of routes and functionality which means testing is a must. I do sometimes wonder if we've over engineered our solution by separating the logic from the views, but we are still able to constantly ship features and have very little defects on production.
@rand0mtv660
@rand0mtv660 2 жыл бұрын
​@@WebDevCody Yeah there really isn't one solution that is fit for every project. I've worked on projects that haven't been touched for 2-3 years and they work the way they need to and that's fine. They were developed by 2-3 people without testing and this separation and once deployed and initial bugs were squashed there was no need to work on them regularly. They just do what they need to and they work for people that use them daily. I do think more and more about separating logic and UI, but I just haven't used it in practice that often. I'm still just kinda thinking about it more than doing it. I think the biggest issue as always with stuff like this is just getting everyone in the team(s) on the same page and enforcing these patterns, whatever they may be.
@romanmunar
@romanmunar 2 жыл бұрын
Wouls like to know what your thoughts are on state machines. It kindof touches on this decoupling of the logic from rendering the ui.
@WebDevCody
@WebDevCody 2 жыл бұрын
They sounds like an interesting concept, I haven’t played around with them much yet. I feel they have a very specific use case
@romanmunar
@romanmunar 2 жыл бұрын
@@WebDevCody Yeah I agree it's quite niche. They are more like logic orchestration than a state management solution
@judegao7766
@judegao7766 2 жыл бұрын
Your controller looks like something that can be nicely achieved by mobX.
@WebDevCody
@WebDevCody 2 жыл бұрын
Agreed someone showed me mobx and it seems almost identical
@awekeningbro1207
@awekeningbro1207 2 жыл бұрын
I knew backend used MVC architecture, never knew frontend has it too
@oussamasadiki7377
@oussamasadiki7377 2 жыл бұрын
why would nextjs die?
@WebDevCody
@WebDevCody 2 жыл бұрын
My point is all software libraries and frameworks become deprecated after x amount of years
@mumk
@mumk Жыл бұрын
this is why React is a library, not a framework
@AlexSpieslechner
@AlexSpieslechner 2 жыл бұрын
you pretty much made a weird react vue2 hybrid frankenstein.
@WebDevCody
@WebDevCody 2 жыл бұрын
It is ALIVE
@hafidmahdi1329
@hafidmahdi1329 2 жыл бұрын
i think this pattern is really good with solidjs, decoupled logic from your view, and your view function doesn't have to be small as possible to handle re-render because in solid, function it's just call once and reactivity only happen in the accessor of your state
@donnyroufs551
@donnyroufs551 2 жыл бұрын
I agree with the whole react-testing-lib fiesta. Jest also triggers me by the fact that you are allowed to globally mock dependencies, it truly promotes spaghetti code. Not sure if I like the way you are forcing the user to know when to re-render though. In my personal projects I use Mobx which keeps me to my true OO side and gives me reactivity for any framework I hook it up with
@WebDevCody
@WebDevCody 2 жыл бұрын
For sure, this approach was kind of a smelly approach and I don’t use this at work. More thought would need to go into what I did here and I wouldn’t use this on a real project. This was more of a thought experiment.
@WebDevCody
@WebDevCody 2 жыл бұрын
I need to look into mobx again. I know redux and mobx probably provide the same decoupling I’m doing with this MVC approach
@donnyroufs551
@donnyroufs551 2 жыл бұрын
@@WebDevCody for the user it doesnt change a thing, you can decorate your classes e.g makeAutoObservable(UserController) and hook it up in react by wrapping it with an observer HOC. Under the hood its all event driven. I have been experimenting with MVVM, mobx and react and its pretty neat so far. Need a bigger proj to test this on tho
@WebDevCody
@WebDevCody 2 жыл бұрын
@@donnyroufs551 yeah these are all fun concepts to play with but it’s hard to gauge how they scale without a real project with many devs
@asdqwe4427
@asdqwe4427 2 жыл бұрын
I think you make a fine point but it feels wrong together with react. Context fits a bit poorly here.
@WebDevCody
@WebDevCody 2 жыл бұрын
I think it has merit. React easily becomes a tangled mess of components hacked together without real structure. I’d rather treat react as the dumb render library it was made to be and find alternative approaches for state management
@asdqwe4427
@asdqwe4427 2 жыл бұрын
@@WebDevCody yeah, I’m all for making react more testable. Currently there can often be crazy amounts of mocking going on.
@asdqwe4427
@asdqwe4427 2 жыл бұрын
Don’t think you need the render function, one could create something similar to redux connect and make all state and contexts used into props
@lihinfei8334
@lihinfei8334 2 жыл бұрын
you just remind me vue in reactjs
@WebDevCody
@WebDevCody 2 жыл бұрын
That’s a great comparison
@ГенаПетров-н5ы
@ГенаПетров-н5ы 2 жыл бұрын
Over engineering is very evil thing
@WebDevCody
@WebDevCody 2 жыл бұрын
And too simplistic of code leads to unmanageable and tangled codebases. There is a sweet spot in between too simple and too complex, and that’s the line we are always trying to figure out on our projects.
@chukwuemekaajima8373
@chukwuemekaajima8373 2 жыл бұрын
This is just another layer of unnecessary abstraction, React best practice demand that you split your component into smaller standalone pieces if you discover your component is doing too much or is becoming too large. I think this is what your state management library (e.g redux) should be doing. All your data manipulation should be done in your state manager and then send out a data tree that the component should use. Anyways it's always good see other perspective of how things can be done.
@WebDevCody
@WebDevCody 2 жыл бұрын
I could see that. I think the main selling point comes from if you and your team agree unit testing the logic behind your react components is important, than doing this type of abstraction can help with that; otherwise, if you don’t care about unit tests this approach isn’t worth it.
@zlackbiro
@zlackbiro 2 жыл бұрын
This is not the code, this is a spaghetti... Btw, next time you should note the people that you using Next.js an giving the example inside Next.js. "Decoupling" things are not the same in React.js and you should not overengineering already simple stuf in React, especially in Next.js.
@WebDevCody
@WebDevCody 2 жыл бұрын
To each their own
@reliable_tech_innovations
@reliable_tech_innovations 2 жыл бұрын
You lack a fundamental understanding of what nextjs does. You can cd into the directory of a react project in next and run the react app as a standalone app. Lets use react but not actually use react. If you have to do all of this in order for your software to be viable then find another framework or do it in pure javascript. Why choose react and then not take advantage of any of the benefits of react.
@komodoutd
@komodoutd 2 жыл бұрын
Just use Angular lol
@WebDevCody
@WebDevCody 2 жыл бұрын
Lol
@smajdovamanka
@smajdovamanka 2 жыл бұрын
This is just MobX with extra steps
@WebDevCody
@WebDevCody 2 жыл бұрын
I’ve never used mobx, so if that’s the case I need to check it out
@walterlol
@walterlol 2 жыл бұрын
This is such a bad approach. Why dont you have a container comp that is attached to business logic and a dumb component that is agnosit?
Live refactoring a subscriber's React code
32:32
Web Dev Cody
Рет қаралды 117 М.
How I like to test my react components
19:51
Web Dev Cody
Рет қаралды 25 М.
УЛИЧНЫЕ МУЗЫКАНТЫ В СОЧИ 🤘🏻
0:33
РОК ЗАВОД
Рет қаралды 7 МЛН
24 Часа в БОУЛИНГЕ !
27:03
A4
Рет қаралды 7 МЛН
Непосредственно Каха: сумка
0:53
К-Media
Рет қаралды 12 МЛН
Why Use React for Game Development ?
8:53
JSLegendDev
Рет қаралды 4,5 М.
Goodbye, useEffect - David Khourshid
29:59
BeJS
Рет қаралды 504 М.
This is the Only Right Way to Write React clean-code - SOLID
18:23
I tried React and it Ruined My Life
1:19:10
Tsoding Daily
Рет қаралды 156 М.
Why I avoid useEffect For API Calls and use React Query instead
17:45
Making React Context FAST!
33:34
Jack Herrington
Рет қаралды 90 М.
React Architecture and Best Practices • Alexander Kondov
54:29
You Might Be Using Typescript Wrong...
15:32
Theo - t3․gg
Рет қаралды 196 М.
Live refactoring a subscribers React SPA anime application
31:51
Web Dev Cody
Рет қаралды 28 М.
Single Responsibility Principle in React (Design Patterns)
16:50
Cosden Solutions
Рет қаралды 51 М.
УЛИЧНЫЕ МУЗЫКАНТЫ В СОЧИ 🤘🏻
0:33
РОК ЗАВОД
Рет қаралды 7 МЛН