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.
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.
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.
- Creates a context that components can read values.