Context api and Use of it

Zain Ahmed
3 min readSep 5, 2020

--

what is Context api let’s find out

Context api is nothing but a simple solution for a parent to pass states to there nested child also called props drilling to nested

now let take a scenario in which you have a products and in products you have cars so let take an example that state for products are define in app.js main file and in main file you have calling product component like this

app main.js

so here are state and we passing the states as props to Product component

Product component.js

here is product component where we pass cars props to Cars component and let see Cars component

Cars components

so as we see the is a chain or props we are passing just like callback hell its may be props hell also call props deep drilling , so for make it more easy and usable let work with context api init

first we define our store where we define states for products

provider file

this is provider for product where we define initial state as we have empty array u can define initial state whatever you want then we pass this initial state to const ProductProvider which is wrap in createContext and then we wrap our return funtion with ContextStore .provider and place store value to it so then we will get this initial state to different components also we can define function and pass it just like state to provider.

now let see we have reducer to update states

reducer file

no new same as redux we have a type for case and updating state with action.payload

Cars component

so here we are in Cars component just import contextstore from product provider file and warp in useContext hook and get the state which we define in provider so we have the product state and we loop it. let see product component

prodcut file

so if we see our product component we can see there is no props passing to cars as pervious

thats all,

fact

its not an alternate for redux as its has its own pros and corns as it can’t persist data so you need to use local storage as will .

i also made an Expense Tracker with Context api on React Native you can get it from

hope you get some info with this artical , if you learn any thing from this please support me on my You tube channel

--

--

Zain Ahmed
Zain Ahmed

Written by Zain Ahmed

Hello everyone, I am Zain Anmed a software engineer by profession, passionate about trying different technologies and trying some other cool stuff.

No responses yet