The object passed as the value prop to the Context provider changes every render
Asked Answered
O

3

14

I have this error:

src/index.js Line 9:36: The object passed as the value prop to the Context provider (at line 9) changes every render. To fix this consider wrapping it in a useMemo hook react/jsx-no-constructed-context-values

I am not sure how to use useMemo in this case.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import FirebaseContext from './context/firebase';
import { firebase, FieldValue } from './lib/firebase';
import './styles/app.css';

ReactDOM.render(
  <FirebaseContext.Provider value={{ firebase, FieldValue }}>
    <App />
  </FirebaseContext.Provider>,
  document.getElementById('root')
);
Olav answered 23/2, 2022 at 8:7 Comment(1)
did you solve it? I'm having the same issuePlanarian
R
17

I think you need to return FireBaseContext from another component. And in that component you can do useMemo to make ESLint happy.

Something like below (I didn't test this)

import { useMemo } from "react";
import ReactDOM from 'react-dom';
import App from './App';
import FirebaseContext from './context/firebase';
import { firebase, FieldValue } from './lib/firebase';
import './styles/app.css';


ReactDOM.render(
  <FireBaseWrapper />,
  document.getElementById('root')
);

const FireBaseWrapper = () => {
  const fireBaseProviderValue= useMemo(() => ({ firebase, FieldValue }), [firebase, FieldValue]);

return (<FirebaseContext.Provider value={fireBaseProviderValue}>
    <App />
  </FirebaseContext.Provider>)
}
Rentroll answered 24/2, 2022 at 18:18 Comment(1)
is this actually necessary at such a high level of the render tree? I'm going to do it to make eslint happy but wondering how necessary it really isGlyphography
V
1

I had this same problem and didn't necessarily want to use 'useMemo'. I instead pasted this eslint command above the line in question, and it disables the eslint flag.

    // eslint-disable-next-line react/jsx-no-constructed-context-values

This then allowed me to deploy without the issue.

Vories answered 18/5, 2023 at 15:10 Comment(1)
Turning off the warning, which has a good reason for being there in the first place, is not a solution.Alvinia
O
1

You can simplify it further with the following snippet:

const FireBaseWrapper = () =>
  <FirebaseContext.Provider value={useMemo(() => ({ firebase, FieldValue }), [firebase, FieldValue])}>
    <App />
  </FirebaseContext.Provider>;
Oxide answered 23/9, 2023 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.