React Hooks: Context API + useContext

Context API in React with Hooks.png

What is Context?

Context provides a way to share values between components. also, properties and functions can be accessed from anywhere in your project This avoids a problem known as prop drilling..

1_Ha2vNB0ILaYKPXk6oyTZSQ.png

How To Create a React Context

The syntax of a React Context is:

// Create the context
const AuthContext = createContext(); 

// A function that you would pass children components into.
function AuthContextProvider({ children }) {
  return (
    <AuthContext.Provider value={/*  value */}>
        {children}
    </AuthContext.Provider>;
}

What is a provider? The provider acts as a delivery service. When a consumer asks for something, it finds it in the context and delivers it to where it’s needed.

value ~ You can pass multiple values at once by passing in an object too !

How to Consume Context

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { AuthContextProvider} from "./components/Context/AuthProvider";
import { ChakraProvider } from "@chakra-ui/react";

ReactDOM.render(
  <React.StrictMode>
      <AuthContextProvider>
          <App />
      </AuthContextProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

How do I use the context?

Now you can access the value using the use context hook. The use context hook accepts the context object and returns the context value.

The syntax for useContext :

const useAuth= () => useContext(AuthContext)

This value will always be up to date as you change the value pass to the Provider, useContext hook will make sure that you get the latest update value at each time. you can simply import it and use it :-

import  useAuth from  "./context/userContext"

now we can use the value , like:

const {userId,isUserloggedIn} = useAuth();

Just to wrap it up, React Context API is introduced to avoid props drilling in React applications.

Next Blog: useReducer Hook

Feel free to ask any questions if you have in the comment section below. Thanks for reading !

Connect With Me!

Twitter: twitter.com/omkarBorude

LinkedIn:linkedin.com/in/omkar-borude-b4583016b

GitHub: github.com/omkarborude

Website:omkar-borude.netlify.app