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 Provide and Consume State

Tyler McDonald
.a{fill-rule:evenodd;}techdegree seal-36
Tyler McDonald
Full Stack JavaScript Techdegree Graduate 16,700 Points

Does the Context API use inheritance, or composition?

After reading up on the React docs, it seems like they are advising to be careful when using Context:

Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.

And then another useful article on the React site about composition vs. inheritance.

In this section, we will consider a few problems where developers new to React often reach for inheritance, and show how we can solve them with composition.

Does the React Context API use inheritance or composition?

1 Answer

Kevin D
Kevin D
8,646 Points

I think they're different concepts!

As the docs say, React Context should be used when you have some global state that needs to be re-used in other components in your app.

The way I see component composition is just extracting out your components into smaller pieces to "compose" bigger components. This can help with the prop drilling problem - which is when you end up passing through a value/prop through many intermediate problems.

const App = () => {
const { data } = useQuery('...'); // fetches some data

return (
      <ChildComponent value={data}/> // with component composition, you can just pass in the value directly to the component