0

So I've been reading about using react context to avoid drilling of props. A basic example is has a component which provides a value which itself is kept in the Component state:

<ThemeContext.Provider value={this.state.shared, updateMyState}>

and a Consumer that uses that value.

Can I share the value of an exported list instead or should the Component which provides the Provider always refer to its state or a static value?

Here is what I mean:

file ./list:

export const list = [];
export const updateList = (val) => list.push(val);

file ./provider:

import Provider from './provider'
import {list, updateList} from ./list

{Provider, Consumer} = React.createContext();
export ProviderComponent = () => 
   <Provider value={list, updateList}>
      <children>
   </Provider>
}
Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75
  • If I understand what you're asking correctly — you can add functions / methods to the Provider, and then reference those in state to pass them through to the Consumer. – Colin Ricardo Jan 19 '19 at 12:41
  • @Colin Are you saying that the above example is incorrect, and I should first store the reference to the list in the `ProviderComponent` ? The list object is the core of my question – Bartlomiej Lewandowski Jan 19 '19 at 12:46

1 Answers1

0

Yes, you can. If you're concerned about importing module multiple times creates multiple instances of list object, when you do an import like import { a, b } from './file, ./file is referenced only once (Check out this stackoverflow answer).

I think your syntax is slightly off though, it should be

<Provider value={{ list, updateList }}>
Derek Nguyen
  • 11,294
  • 1
  • 40
  • 64