1

I have a Class Component in a React App. It works. Then I need a global variable and reached to the React's Contexts. I create Context and can consume its value.

But I need to update its value, I read a lot and it seems I have to use React Hooks to update Context value. But my components are Class Components and there I cant use hooks.

My question is, If I want to use Contexts, I cant use Class Components? Right now Im learning React and encountered to Hooks many times. If hooks very important thing, This means we have to use Function Components all the times?

What I have to do? I just need to update my global variable and use its value.

Fcoder
  • 8,466
  • 17
  • 54
  • 90

2 Answers2

1

Please visit this link, https://www.taniarascia.com/using-context-api-in-react/ and How to update React Context from inside a child component?. it is explained in this link, you can do this way :

class LanguageSwitcher extends Component {
  render() {
return (
  <LanguageContext.Consumer>
    {({ language, setLanguage }) => (
      <button onClick={() => setLanguage("jp")}>
        Switch Language (Current: {language})
      </button>
    )}
  </LanguageContext.Consumer>
);
  }
}
Neelam Soni
  • 729
  • 5
  • 12
1

If I want to use Contexts, I cant use Class Components?

No, you can use context either in Class Components. See Context section in docs, all examples are with classes.

We have to use Function Components all the time?

No, you can use any approach you see fit.

But, there is no actual reason to use Class Components any more (except implementing Error Boundary). React officially recommends using hooks and composition, therefore the preferable approach is Function Components.

What I have to do? I just need to update my global variable and use its value.

A global variable as the name stands, its global to the application's scope (and not bound to component's scope like state). You can update it from everywhere.

const globalObject = { name: `myVar` };

// Can be updated from any scope as you keep the reference.
const FunctionComponent = () => { globalObject.name=`a`; return <></>; }

// Outer scope
globalObject.name=`b`;
Dennis Vash
  • 31,365
  • 5
  • 46
  • 76