Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,393 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!