E
E
exelenet2020-02-04 23:56:02
React
exelenet, 2020-02-04 23:56:02

Dependency Inversion in React! Why is this an anti-pattern?

Good day to all! This question haunts for a long time: why is it bad form to call methods from a child component in react? Doesn't this increase reusability and loose bonding between parent and child?
Here, I even drew a schematic
5e39da46cbc97456324939.png
I.e. store - the domain model of the application organized through redux, mobx or even hooks + context, everything is clear here, everything is clear
with the container, it is the link between the model and the component (Widget).

The most interesting next. A widget is an encapsulated interface unit that is supposed to work independently of the application, and start working immediately when it is moved somewhere else. He himself has, as it were, wires that just the container component connects to the model to communicate with the outside world. It, in turn, consists of simple, but at the same time independent components (circles on the diagram). Communication between them proceeds through interfaces, actually the squares in the figure (thanks to useImperativeHandle and ref, which are not recommended to be used).

The source of truth is always 1. Only the sources themselves are not one (which is not a crime). For business logic in the model, for the graphical interface - in the components. And yes, I forgot to display the arrow in both directions between the container and the widget. So why is it not recommended to do this? :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-02-05
@Robur

Share where did you get that this is an anti-pattern?
And where is the dependency inversion?
In general, what you described is not only "possible", but also a common scheme.
Widget provides an interface for working with it - such and such props can be passed, such and
such methods it can accept.
Further container organizes it all for him. And here Widget is the source of api - what is written in its logic and in props - and it should be used.
What kind of Container is already all the same as long as it uses the Widget correctly.
If you want to pass components to the Widget that this Widget should render internally, this is also normal, for the Widget it's just another one of the props.
a classic example (not counting the children already built into JSX) is a button with an icon, the button in props declares that it has the ability to get an icon, and assumes something about it (for example, it should be square, no more than 40 pixels, etc.
) further you write in Container No knowledge about your container is needed in the button. <IconButton icon={<Icon/>}>Hello</IconButton>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question