useContext hook

pravindvarma@gmail.com

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.

app.js

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

Context.js

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

Child.js

import * as React from 'react';
import { useContext } from 'react';
import { TestContext } from './Context';
const Child = () => {
  const user = useContext(TestContext);
  return (
    <>
      <div>Child </div>
      <strong>{user}</strong>
    </>
  );
};
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