Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React by Example Building the Application Changing Guest Name in State

Gordon Freeman
PLUS
Gordon Freeman
Courses Plus Student 930 Points

Should the call-back-funciton always be at the same level Component where the related-State exists?

So the callback function should always be at the same level component where the related-States exist? Can I just put setName callback at the Guest Component? Instead Top level component(where the name State exists) so that I can just pass it down lesser number of times through lesser number of Components

1 Answer

Seth Kroger
Seth Kroger
56,412 Points

The short answer is yes. When you consider it, the way React works with data only flowing downward from parent to child the callbacks are the only way to change the the data in state. If you wrote the callback in an intermediate level like Guest, you'd still need another callback to bubble that change up to the component with the state because Guest wouldn't have direct access to App's state. So, rather than write two duplicate callbacks, we write one and pass it all the way down.

Yes, it makes for passing a lot of callbacks though a lot of different levels, but that is the style React gravitates to with one-way binding.

Gordon Freeman
Gordon Freeman
Courses Plus Student 930 Points

That makes sense! Thanks for your time and great answer!