LeoDT
LeoDT

Reputation: 80

Why do I need the new Context API? The value is already imported

The new Context API require the consumer to import the context from where it's created.

So why the consumer needs to define contextType? I can just use the imported value.

import ThemeContext from './context/theme';

class Component {
  render() {
    return (
      <div>{this.context}</div>
    );
  }
}

Consumer.contextType = ThemeContext; // why?

If I have a component ComponentA in package PackageA, and it requires a context. How to define the context for it?

// PackageA/ComponentA.js, managed by npm/yarn
import PackageContext from './context';

class ComponentA {}

ComponentA.contextType = PackageContext;

// ===========================================

// src/App.js
import ComponentA from 'PackageA/ComponentA';

const MyContext = React.createContext();

function App() {
  return (
    <MyContext.Provider value="app context">
      <ComponentA />
    </MyContext.Provider>
  );
}

The only way I came up is like this. But I just can't like it.

// src/ComponentA.js
import ComponentA from 'PackageA/ComponentA';

ComponentA.contextType = MyContext;

export default ComponentA;

// And just import this component instead of the one in `PackageA`,
// although we can still use it because it's modified.

Upvotes: 1

Views: 155

Answers (1)

Estus Flask
Estus Flask

Reputation: 222538

contextType static property is supposed to be used with class components together with context instance property and serve as an alternative to ThemeContext.Consumer. In case of functional component it affects nothing, Consumer.contextType isn't needed.

A counterpart to contextType in functional component is useContext hook, since React 16.8:

function Consumer() {
  const theme = React.useContext(ThemeContext);
  return (
    <div>{theme}</div>
  );
}

Upvotes: 1

Related Questions