Context Api

Context Api

In a typical React application, data is passed top-down (parent to child) via props, but this can be difficult for certain types of props (e.g. locale preference, UI theme) that are required by many components which are Nested at different levels within an application.

Here, we will understand how we use Context to pass the data between components at different nesting levels.

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Context is primarily used when some data needs to be accessible by many components at different nesting levels.

There are three simple steps which we can follow :

  1. Create a context
  2. Provide context
  3. Consume context with useContext hook

Create a context

To use the Context API, we have to create a context first. A context is like a source where the provider gets the data from and passes it to the components. We can create a context with the help of createContext method.

/*  MyContext.js  */

// Import createContext method from React
import {createContext} from 'react'

// Create and export context with a default value
export const MyContext = createContext(defaultValue)

Provide context

After we create our context, we have to provide it to the component tree. We do that by wrapping the component that will use the context's data with a context provider.


/*  MainApp.jsx  */

//Import the context created
import { MyContext } from 'your-path/MyContext.js'
// Import MyComponent
import MyComponent from 'your-path/MyComponent.jsx'

//App Component
const App = () => {
    return (
        // Wrap MyComponent with MyContext.Provider and give it a value
        <MyContext.Provider value={contextValue}>
            <MyComponent />
        </MyContext.Provider>
    )
}

Consume context with useContext hook

useContext hook allows us to access the current value of a context. This value is determined by the value prop of the nearest . ernestoangulo.hashnode.dev/manage-global-st...


/*  MyComponent.jsx  */

// Import useContext
import { useContext } from 'react'
// Import the context created
import { MyContext } from 'your-path/MyContext.js'

// MyComponent
const MyComponent = () => {
    // useContext hook returns the current value of the context
    const contextValue = useContext(MyContext)

    //...
}

Thats all , Hope you enjoyed and learned few things for your next big react app