Do multiple declarations of the same Provider create new instances in React?

Viewed 47

Question 1 In React 16.3.x will Providers share the same instance regardless of hierarchy?

Question 2 Will the LazyloadProvder with a shared value be the same instances?

const value1 = {wow: () => {}}
<App>
  <LazyloadProvider value={value1}>
    <LazyloadConsumer >
     <h1>hello sibling 1</h1>
    </LazyloadConsumer>
    <LazyloadProvider value={value1}>
      <LazyloadConsumer>
       <h1>hello sibling 1 - child nest</h1>
      </LazyloadConsumer>
    </LazyloadProvider>
  </LazyloadProvider>
  <LazyloadProvider value={value1}>
    <LazyloadConsumer>
     <h1>hello sibling 2</h1>
    </LazyloadConsumer>
  </LazyloadProvider>
</App>

Question 3 What about with different values?

const value1 = {wow: () => {}}
const value2 = {wow: () => {}}
const value3 = {wow: () => {}}
<App>
  <LazyloadProvider value={value1}>
    <LazyloadConsumer >
     <h1>hello sibling 1</h1>
    </LazyloadConsumer>
    <LazyloadProvider value={value2}>
      <LazyloadConsumer>
       <h1>hello sibling 1 - child nest</h1>
      </LazyloadConsumer>
    </LazyloadProvider>
  </LazyloadProvider>
  <LazyloadProvider value={value3}>
    <LazyloadConsumer>
     <h1>hello sibling 2</h1>
    </LazyloadConsumer>
  </LazyloadProvider>
</App>

I don't quite follow this github issue but I think it talking about something similar https://github.com/facebook/react/issues/13346

1 Answers

Context Consumer receives a value from nearest Provider.

In case <LazyloadConsumer> is a child of <LazyloadProvider value={value2}>, <LazyloadProvider value={value1}> doesn't affect it.

It's the same logic as in variable scopes:

const foo = 1; // won't affect inner scope any way
{
  const foo = 2;
  console.log(foo); // 2
}
Related