简体   繁体   中英

Using a global object in React Context that is not related to state

I want to have a global object that is available to my app where I can retrieve the value anywhere and also set a new value anywhere. Currently I have only used Context for values that are related to state ie something needs to render again when the value changes. For example:

import React from 'react';
const TokenContext = React.createContext({
    token: null,
    setToken: () => {}
});

export default TokenContext;

import React, { useState } from 'react';
import './App.css';
import Title from './Title';
import TokenContext from './TokenContext';

function App() {

  const [token, setToken] = useState(null);


  return(
    <TokenContext.Provider value={{ token, setToken }}>
      <Title />
    </TokenContext.Provider>
  );
}

export default App;

How would I approach this if I just want to store a JS object in context (not a state) and also change the value anywhere?

The global context concept in React world was born to resolve problem with passing down props via multiple component layer. And when working with React, we want to re-render whenever "data source" changes. One way data binding in React makes this flow easier to code, debug and maintain as well. So what is your specific purpose of store a global object and for nothing happen when that object got changes? If nothing re-render whenever it changes, so what is the main use of it?

Prevent re-render in React has multiple ways like useEffect or old shouldComponentUpdate method. I think they can help if your main idea is just prevent re-render in some very specific cases.

Use it as state management libraries like Redux.

You have a global object (store) and you query the value through context, but you also need to addforceUpdate() because mutating the object won't trigger a render as its not part of React API:

const globalObject = { counter: 0 };

const Context = React.createContext(globalObject);

const Consumer = () => {
  const [, render] = useReducer(p => !p, false);
  const store = useContext(Context);

  const onClick = () => {
    store.counter = store.counter + 1;
    render();
  };

  return (
    <>
      <button onClick={onClick}>Render</button>
      <div>{globalObject.counter}</div>
    </>
  );
};

const App = () => {
  return (
    <Context.Provider value={globalObject}>
      <Consumer />
    </Context.Provider>
  );
};

编辑迷人的湖-iyk04

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM