Alex Kuzmin
Alex Kuzmin

Reputation: 171

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

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')
);

Upvotes: 17

Views: 25471

Answers (3)

Amanuel T
Amanuel T

Reputation: 46

You can simplify it further with the following snippet:

const FireBaseWrapper = () =>
  <FirebaseContext.Provider value={useMemo(() => ({ firebase, FieldValue }), [firebase, FieldValue])}>
    <App />
  </FirebaseContext.Provider>;

Upvotes: 3

RubberDucky73
RubberDucky73

Reputation: 19

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.

Upvotes: 1

Tommy
Tommy

Reputation: 171

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>)
}

Upvotes: 17

Related Questions