Home > AI > Frontend > ReactJS >

useContext

Example:


import React, {useContext} from 'react';


const themes = {
  light: {
    foreground: "red",
    background: "blue"
  },
  dark: {
    foreground: "blue",
    background: "red"
  }
};

const ThemeContext = React.createContext(themes.light);

export default function App() {
  return (
    <ThemeContext.Provider value={themes.dark}>
      <Toolbar />
    </ThemeContext.Provider>
  );
}

function Toolbar() {
  const theme = useContext(ThemeContext);

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

Leave a Reply