useContext example

βš™οΈSelect the language

Level One

Level Two

Level Three

πŸ‹This is a lemon.

useContext

The React context provides an easier way to share the data across nested components, e.g. global state, user settings theme etc.

πŸš€ Usage of context:

  • Creating the context
  • Providing the context (in the parent component)
  • Consuming the context (inside the inner componenet)

1. Creating the context

const Context = createContext('Default Value');

2. Providing the context - share the needed data as a value prop using Context Provider component

function App() {
  const selectedLanguage = 'english';
  return (
    <Context.Provider value={selectedLanguage}>
      <Card />
    </Context.Provider>
  );
}

3. Consuming the context - get the data from the useContext()

import { useContext } from 'react';
function Card() {
  const value = useContext(Context); // value = "english"
  return <h2>{value}</h2>;
}