React Answers

How to declare global variables in React?

Spread the love

To declare global variables in React, we can use the React context API.

For instance, we write

const themes = {
  light: {
    foreground: "#000000",
    background: "#eeeeee",
  dark: {
    foreground: "#ffffff",
    background: "#222222",
const ThemeContext = React.createContext(themes.light);

class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />

to call React.createContext to create the ThemeContext.

Then we wrap ThemeContext.Provider to let the Toolbar component access the context values.

Then we use the useContext hook to access the theme.light value by writing

function Toolbar() {
  const theme = useContext(ThemeContext);
  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      I am styled by theme context!

We call `useContext` with `ThemeContext` to get the value of `ThemeContext` as the value of `theme`.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *