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;
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>
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>
)
There's an alternative way of consuming the data by using useContext hooks
const ctx = useContext(Context)
return (
({ctx.isLoggedIn && <Login></Login>}
)
This helps us to reduce the code and avoid the use of function
Top comments (0)