T
T
The_good_game2021-09-27 07:06:44
React
The_good_game, 2021-09-27 07:06:44

How to correctly pass the context to subChild components located in other modules?

When I create a context with React.context for a parent component, I can't use that context in one of the child components that is in another module. In order to do this, I need to import the created context variable in the parent component. But is it then necessary to use React.context if everything will work without it?

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

let someContext = React.createContext(null);

export default function ParentComp() {
  return (
    <someContext.Provider value={{key: prop}}>
      <ChildComp />
    </someContext.Provider>
  )
}

//ChildComp.js
export default function ChildComp() {
  return (
    <div>
      <SubChildComp />
    </div>
  )
}

//SubChildComp.js
import { useContext } from 'react';

export default function SubChildComp() {
  let contextData = useContext(someContext) // Error: someContext is not defined;

  return (
    <div />
  )
}

//но так работает
//parentComponents.js
import React from 'react';

let someContext = React.createContext(null);
// можно ли не использовать  React.createContext, someContext.Provider и т.д.
// просто создав переменную someContext и присвоив ей объект из ParentComp?

export default function ParentComp() {
//...
}

export { someContext }

//ChildComp.js
export default function ChildComp() {
//...
}

//SubChildComp.js
import { useContext } from 'react';
import { someContext } from '../../parentComponents'

export default function SubChildComp() {
  let contextData = useContext(someContext) // всё работает;
//...
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-09-27
@The_good_game

It seems that you do not understand why the context is needed at all.
It allows you to pass a value down several levels. At the same time, if the value in the context changes, then all components that use it will be re-rendered.
You can also pass some constant value, for example, an instance of some store, as the same react-redux does. In this case, value change tracking is not used (it is constant), but there is an architectural benefit - this is such a kind of DI in layout. Which, for example, can be changed in tests or somewhere else. That is, the component is not nailed to the imported value, but receives it as parameters, with a later dependency resolution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question