Abhay Namdeo
Abhay Namdeo

Reputation: 31

When should I use a this.context vs Consumer in the New Context API in React?

There are two styles for using the context data in the Child components: this.context and using the <myContext.Consumer>{(contextData) => {return(<div>{myContextData}</div>}}</myContext.Consumer>

when should I use the former vs latter?

Upvotes: 2

Views: 1538

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

There are not two but three ways to use context in v16.8.0 and above. The choice of which one you should use depends upon your use case.

The first one i.e using static contextType is the simplest of the two to use which allows you to use context throughout your class component. You can acchieve the same behaviour using render props pattern but then you have to wrap your component within another functional component.

So the choice, although a matter of personal preference and wouldn't impact performance of debugging much is simple to make.

  • If you want to make use of just one context within the component, you can make use of static contextType to define it.
  • However, if you have more than one context which you want your component to use, then you can't achieve that with the first pattern,so you have to make use of render props pattern

An example of the above is say you are using a ThemeProvider and your component just uses that you can write it simply as below using first pattern

class MyComponent extends React.Component {
   ...
}
MyComponnet.contextType = ThemeContext;
export default MyComponent

with render prop pattern you would need to write it as below given you want to use context outside of render method too

class MyComponent extends React.Component {
   ...
}

export default (props) => (
    <ThemContext.Consumer>
        {(context) => <MyComponent {...props} context={context} /> 
     <ThemeContext.Consumer>
)

However say you want to use two context within MyComponent ie. say a ThemeContext and ShortCutContext to listen to keyboard shortcuts you would write it using render props like below

class MyComponent extends React.Component {
   ...
}

export default (props) => (
    <ShortcutContext.Consumer>
        {(sCon) => (
         <ThemContext.Consumer>
            {(tCon) => <MyComponent {...props} themeContext={tCon} shortcutContext={sCon} /> 
         <ThemeContext.Consumer>
        )}
    </ShortcutContext.Consumer>

)

There is a third way which is useContext, which allows you to use context within functional components using hooks pattern. If you are writing your App with hooks, you can make use of useContext which allows you to have multiple contexts within your App too

You can use multiple contexts using useContext as below

const MyComponent = () => {
   const shortcutContext = useContext(ShortcutContext);
   const themeContext = useContext(ThemeContext);
   ...
}

Upvotes: 5

Related Questions