Thijs Koerselman
Thijs Koerselman

Reputation: 23271

React passing data via props vs method call

Say I have a component X which renders a text input field + a child component Y. Y uses the text from the input field to render something else.

To get the data, X listens for a change event from the text field, and then grabs its updated content via a ref.

Now as I understand it I can pass the data to child Y in two ways.

1) X stores the new data in its state, so its render method is triggered, and here I pass the data to Y using props like <Y something={data}/>

2) X calls a method on Y by using it ref like this.refs.y.setSomething(data). In this case I don't need to store the data in the state of X.

So apart from storing state in X, what are the reasons to choose one over the other?

Upvotes: 0

Views: 773

Answers (1)

Matti John
Matti John

Reputation: 20477

You should pass the data into the child component using props, as in the documentation. You can think of the props as the function arguments for the child components.

Other than being the idiomatic way to do this in React, I can think of a few reasons why you should do this. Firstly, calling a method like this.refs.y.setSomething(data) will mean that you need to implement code for storing the state in Y. So you haven't had to set state in X, but you do it in Y instead.

More importantly, if X for some reason unmounts Y during a re-render and then later remounts it, you will have lost the state in Y. But if you are passing in props, then Y would receive the same props before and after it's unmounted.

Upvotes: 2

Related Questions