Context
The Context API in React is an easy way to manage the state of some information. It lets the parent component pass the information down to any other component further down the tree hierarchy without needing to pass it as a prop. It can be used in combination with the useState()
hook to change the state. Typical use cases are passing themes (e.g. color, paddings, font sizes, etc.) or the authenticated user.
Benefit
Normally, information on values is passed between components as props. But sometimes it has to be passed down several levels in the tree, also called prop drilling
. In larger applications, this can be complicated and lead to code that is hard to maintain. With Context
this is no longer necessary.
API Implementation
To implement the Context API, it’s necessary to first create the Context using createContext()
. Afterward, the useContext()
hook can be used to read the context from the appropriate component.
Context
- createContext()
- Creates a context that components can read values.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.