useContext hook

Most of the blogs provide code that has parent and child component placed in the same file. The context is available to both the component. For the components which are placed in different files, we have to extract Context in a separate file.


import * as React from 'react';
import './style.css';
import Parent from './Parent';
import { TestContext } from './Context';
export default function App() {
  return (
      <TestContext.Provider value="Context">
        <Parent />


import * as React from 'react';
export const TestContext = React.createContext();


import * as React from 'react';
import { useContext } from 'react';
import { TestContext } from './Context';
const Child = () => {
  const user = useContext(TestContext);
  return (
      <div>Child </div>
export default Child;

The context can now be shared easily across the descendent component easily.

About the Author

Pravin Varma

Tech Lead at Calsoft

You may also like these