DEV Community

Athul A
Athul A

Posted on

Context Api in react

Today I covered the context api concept in react.It is useful to pass value from one component to another component without the use of props chaining.

First of all we need to create a new js file

const Context=React.createContext({
        isLoggedIn : false
});

export default Context;
Enter fullscreen mode Exit fullscreen mode

Now we created a context with the component name Contex which is an object having our value to be passed to other component

Now we need to import this to parent component (Eg:App.js),
and we should wrap the whole return state with the imported component i.e Context

const [isLoggedIn,setLoggedIn] = useState(false);

function loginHandler(){
 setLoggedIn(true)
}

//Value here passed is the vlaue of isLoggedIn variable it will be changed when the user logged In 
<Context.Provider value={{
isLoggedIn:is isloggedIn}}>
  //Rest of the component
</Context.Provider>
Enter fullscreen mode Exit fullscreen mode

so basically when the user is loggedIn the loginHandler will be executed and isLoggedIn wil become true and it will be passed to all component

To consume the passed data

//Ctx will be an object containing our data
return (<Context.Consumer>

   {(ctx)=>{
  return ({ctx.isLoggedIn && <Login></Login>)
}}
  </Context.Consumer>
)

Enter fullscreen mode Exit fullscreen mode

There's an alternative way of consuming the data by using useContext hooks

const ctx = useContext(Context)
return (
 ({ctx.isLoggedIn && <Login></Login>}
)

Enter fullscreen mode Exit fullscreen mode

This helps us to reduce the code and avoid the use of function

Top comments (0)