DEV Community

niirjhor
niirjhor

Posted on

Context API

A React app can use the React Context API to generate global variables that can be passed around. This is an alternative to "prop drilling," which entails passing props from grandparent to child to parent and so on. Context is also marketed as a simpler, lighter way to Redux state management.

Context API is a (sort of) new feature in React 16.3 that allows you to communicate state easily and lightly across the entire project (or part of it).
React.create All you need is Context(). It will give you a customer and a provider. Provider is a component that supplies the state to its children, as its name suggests. It will contain the "store" and serve as the parent of all components that may require it. A component that consumes and uses the state is known as a consumer.
How to use Context API?

  1. Create a folder called contexts under your app's root directory (this is optional). It's only a convention.)
  2. Make a file with the name your context name
  3. Context.js, such as userContext.js, imports and creates a context
  4. Create a component named Provider to wrap the provider, for example. UserProvider
  5. Create a higher-order component named with, for example, withUser, to consume the context.
  6. Finally, export them and
  7. Use them as needed.

Top comments (0)