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

Tyler McDonald
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tyler McDonald
Full Stack JavaScript Techdegree Graduate 16,676 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 (
  <GrandparentComponent>
    <ParentComponent>
      <ChildComponent value={data}/> // with component composition, you can just pass in the value directly to the component
    </ParentComponent>
  </GrandparentComponent>
)
}