19 Feb 2024




Intermediate

In React.js, the useContext hook is a built-in hook that allows functional components to consume values from the Context API. The Context API provides a way to share values, such as global state, between components without passing props through every level of the component tree manually.

Basic syntax of the useContext hook:

Step 1: Creating a Context

In this step, we create a context using React.createContext(). This creates a context object that components can subscribe to.

// Context.js
import React from 'react';

const MyContext = React.createContext();

export default MyContext;

Step 2: Creating a Provider Component

Here, we create a provider component that wraps around the part of the component tree where we want to make the context available.

// MyProvider.js
import React from 'react';
import MyContext from './Context';

function MyProvider({ children }) {
  const sharedValue = 'Hello from Context!';

  return (
    <MyContext.Provider value={sharedValue}>
      {children}
    </MyContext.Provider>
  );
}

export default MyProvider;

Step 3: Consuming the Context

We consume the context in components that need access to the shared data by using the useContext hook.

// MyConsumer.js
import React, { useContext } from 'react';
import MyContext from './Context';

function MyConsumer() {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
}

export default MyConsumer;

Step 4: Using the Provider and Consumer in the App

Finally, we integrate the provider and consumer components into our app's component tree.

// App.js
import React from 'react';
import MyProvider from './MyProvider';
import MyConsumer from './MyConsumer';

function App() {
  return (
    <MyProvider>
      <MyConsumer />
    </MyProvider>
  );
}

export default App;

In this example, the MyProvider component wraps around the MyConsumer component in the App component, ensuring that the context provided by MyProvider is accessible to MyConsumer and its descendants. In this example:

Key points of useContext Hook in react js

  • Context Creation:

    • First, you need to create a context using the createContext function. This function returns a context object, which consists of a Provider and a Consumer.
    • Example:
      const MyContext = createContext();
      
  • Context Provider:

    • Use the Provider component to wrap the part of the component tree where you want to make the context available.
    • The value prop of the Provider sets the value that will be consumed by the components within its scope.
    • Example:
      const MyComponent = () => {
        return (
          <MyContext.Provider value={/* someValue */}>
            {/* Components within this scope can access the context */}
          </MyContext.Provider>
        );
      };
      
  • useContext Hook:

    • The useContext Hook allows a functional component to subscribe to a React context.
    • It takes the context object as an argument and returns the current context value.
    • Example:
      const MyComponent = () => {
        const contextValue = useContext(MyContext);
      
        // Now, contextValue contains the current value of the context
      };
      
  • Dynamic Context Values:

    • Context values can be dynamic and may depend on the state or props of the component.
    • Example:
      const MyComponent = () => {
        const [value, setValue] = useState(/* someInitialValue */);
      
        return (
          <MyContext.Provider value={value}>
            {/* Components within this scope can access the dynamic context value */}
          </MyContext.Provider>
        );
      };
      
  • Nested Contexts:

    • You can nest context providers to create a hierarchy of contexts. Components can then consume the context values at different levels.
    • Example:
      const OuterContext = createContext();
      const InnerContext = createContext();
      
      const MyComponent = () => {
        return (
          <OuterContext.Provider value={/* outerValue */}>
            <InnerContext.Provider value={/* innerValue */}>
              {/* Components within this scope can access both context values */}
            </InnerContext.Provider>
          </OuterContext.Provider>
        );
      };
      
  • Default Values:

    • You can provide a default value when creating a context, and it will be used when a component is not wrapped within a Provider.
    • Example:
      const MyContext = createContext(/* defaultValue */);
      
  • Context with Reducers:

    • You can use the Context API along with useReducer for managing more complex state logic in your application.
    • Example:
      const MyContext = createContext();
      
      const MyComponent = () => {
        const [state, dispatch] = useReducer(reducer, initialState);
      
        return (
          <MyContext.Provider value={{ state, dispatch }}>
            {/* Components can access state and dispatch using useContext */}
          </MyContext.Provider>
        );
      };
      
  • Dynamic Context in Function Components:

    • useContext is particularly useful for dynamically changing context values in functional components.
    • Example:
      const MyComponent = () => {
        const [theme, setTheme] = useState('light');
      
        return (
          <ThemeContext.Provider value={{ theme, setTheme }}>
            {/* Components can dynamically access and update the theme */}
          </ThemeContext.Provider>
        );
      };
      
  • Context in Class Components:

    • While useContext is designed for functional components, you can still use the Consumer component or the this.context property in class components to consume context.
    • Example:
      class MyClassComponent extends React.Component {
        static contextType = MyContext;
      
        render() {
          const { value } = this.context;
          // Render based on the context value
        }
      }
      
  • Dynamic Context Changes and Re-renders:

    • Changes to the context value will trigger re-renders in components that consume the context using useContext.
    • Example:
      const MyComponent = () => {
        const [count, setCount] = useState(0);
      
        return (
          <MyContext.Provider value={count}>
            <ChildComponent />
            <button onClick={() => setCount(count + 1)}>Increment</button>
          </MyContext.Provider>
        );
      };
      
reactjs
usecontext