React by Patrik

React useContext Sample

useContext allows you to consume the context values within a functional component, making it more convenient and concise compared to using the Consumer component.

Here's an example of using React Context and the useContext hook:

import React, { createContext, useContext } from 'react';

// Create a context
const MyContext = createContext();

function ParentComponent() {
  const contextValue = "Hello from Context!";

  return (
    <MyContext.Provider value={contextValue}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

function ChildComponent() {
  // Consume the context using the useContext hook
  const contextData = useContext(MyContext);

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

function App() {
  return <ParentComponent />;
}

In this example, useContext is a hook that allows ChildComponent to access the context value provided by the ParentComponent without needing the Consumer component. So, while React Context itself is not a hook, it can be used in combination with hooks for more concise and modern React code.

Comments