Regarding Dan Abramov's update about Presentational and Container Components, and hooks

Viewed 1398

Presentational/Container components are known as a good separation of concerns pattern in React, and if we search about the topic you'll definitely find Dan Abramov's post regarding that.

But quite some time ago he then updated that post with a statement that can be interpreted that due to the recent adaptability to using Hooks, the presentational/container components pattern is not as recommended as it was before. Since we can create custom hooks that contain that code instead.

How do you interpret what he meant by that?

Having a gigantic custom hook that does all that logic and returns a bunch of variables? And then calling that hook in a component?

Personally I still find container components useful as it separates what is business logic (calling apis and handling the result flow of that) from "UI logic" (storing state for a tab, an animation)

It's easier when you're working with a large scale app to find where the API, redux or graphql calls are being done if they're in its own place, and always following the same pattern. But if we didn't have that, how would we solve this problem and not having a mess of multiple components calling apis and doing its own thing everywhere in the app/tree?

I'm asking this because even when still using container components to only fetch an api and/or get the redux state, and keeping everything tidy, sometimes I still find useful for some components to call the API and do what a "container" would do themselves, to avoid having to pass down props or making a container TOO big/confusing. And it is kind of conflicting having just some components do that and the rest stay in a container component. How would you handle that?

1 Answers

I think presentational components pattern is still relevant with hooks. You can still use the main logic in "Container" component, but in case of hooks, you can remove the concern of using not relevant state from the "Container" component.

For example, you have a list component that directs the main logic and each item has a drop-down in it, is drop-down shown or not is not relevant for the whole list, so its state should stay in the presentational component.

Also, custom hooks are just functions that allow you to re-use state and lifecycle features, so it has no relation to the pattern.

Related