Table of contents
No headings in the article.
Context API is a state management library that allows passing data through the component tree without having to pass props down at every component level.
It's a great alternative to redux and easier to use too.
One challenge with Context API is, it looks for the closest provider above from the component from which it is called and does not consider providers in the components where useContext()
is currently being called.
The explanation of this is:
Consider you are getting state data via useContext()
hook in the App component. I am using the App component as an example because, usually, it is the eldest or the outermost component that wraps all other components. Since there are no other components before the App component, Context API will return an undefined error on the data being queried. This is because Context API always gets state data from a parent component that has a Context API provider wrapper.
So, even if this current component has a Context API wrapper, the context store data would be ignored, and the store data would rather be gotten from its parent's Context API provider wrapper.
The same applies when you are in a component that is not the outermost, that is, the App component.
So what happens when you need to get data directly in the App component?
The snippet below is from an e-commerce store I built. You can check the app here.
The following errors show up and some of them can be confusing. Because in the case here, Items
is an array of objects and defined.
The way around this is to create another component in the App file, use the context data in the component and introduce the component into the App component.
And here we have a list of items with their title.
In conclusion, use the useContext()
hook outside the component where the Context Provider wrapper wraps to get the context store data of the same Context in other to avoid an undefined error.