O
O
Ostic2019-06-13 12:01:36
React
Ostic, 2019-06-13 12:01:36

How not to override Context value (React)?

Hello.
context.js

export const ctx = {
  a: 1
}

app.js
import React, {Provider} from 'react';
import {ctx} from './context';

const CTX = React.createContext(ctx);
function App() {
  return (
    <CTX.Provider value={ctx}>
       <MyComponent />
    </CTX.Provider>
  );
}

can the second time, those directly in
<CTX.Provider value={ctx}>
       <MyComponent />
    </CTX.Provider>

do not specify ctx, but use the one with which the context was created, otherwise it turns out to specify the same thing twice

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-06-13
@Ostic

Option 1:

const CTX = React.createContext();

const App = () => (
  <CTX.Provider value={ctx}>
    <MyComponent />
  </CTX.Provider>
);

But this option will not be convenient if you are going to test components using the context.
Option 2:
const CTX = React.createContext(ctx);

const App = () => (
  <MyComponent />
);

But this option will not be convenient when you need to change the value of the context.
Therefore, if you are going to write tests, it is better to pass the value twice, once for the tests and once for the application to work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question