0

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?

1
  • I added as a comment as it's not an answer to this question. A third way it's using Fluxxor. Creating a store accessible from all components, avoiding all props passing Commented Jan 23, 2015 at 8:22

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's clear to me now. I was using the material-ui components and lot of them have methods to set and get data so I started to wonder. But I understand that the state (if any) should live in the parent component X and not the owned component Y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.