DEV Community

Discussion on: Using a React Component's function from its Parent

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Usually, in situations like this, you'd want to consider lifting the state out of the child component and into the parent. That way, the child is a controlled component that receives a prop telling it what color it should use. The parent maintains the state for the current color, which changes whenever you click one of the control buttons. It passes this color along to the child, which then styles itself. The advantage here is that it's a top-down data flow, with a single source of truth for the state. The child component is also more reusable ("dumb") because it just accepts a color and styles itself; it doesn't worry about the logic of how that color came to be.

The approach described in this article is a bit unconventional because the parent is reaching into its child and relying on that child's implementation to do some work (in this case, it assumes that the child in fact has a method named changeColor). With a top-down data flow, the relationship between the child and parent is more explicit: the parent has a state, and the child takes props. In this case, though, it's more like the child exposing a method to the parent through a ref.

There definitely are legitimate use cases for refs, but I don't think this is one of them.

Collapse
 
sabinthedev profile image
Sabin Adams

Certainly agree 100%! Thanks for pointing this out, the demo in the article was just a simple example of “how” to set up and use the refs. Definitely not the ideal situation to actually use them though 👍