React Hooks useContext Tutorial (With Example)


In this video you will learn useContext hook. This is the hooks implementation to work with context inside functional components. Also if you don't know how context works in React at all we will look on it as well. To learn it better we will build dark/light mode toggler as a real example so make sure that you watch a video until the end.

Let's jump right into it.

Content

So what is context in React and why do we need it at all? This is a way to pass some information which is global in all components at once. Normally we can just communicate between components with parent/child approach. Context helps us to share global things like currentUser data, setted language or theme in all components.

And actually if you are familiar with Redux Provider that we use to wrap all our components with Redux is exactly the context.

<Provider store={store}>
    <App />
  </Provider>,

Here I have empty create-react-app project where we can directly start writing code. If you don't know how to generate react project with create-react-app I made a video on that so go check it out first.

I you can see in browser I have just a single h1 tag and it's our App.js component. Let's have a look. So it's a normal stateless React component with markup inside.

Let's say we want to create a theme global configuration with light/dark mode and pass it in all components.

index.js

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

ReactDOM.render(
  <React.StrictMode>
    <ThemeContext.Provider value={themes.dark}>
      <App />
    </ThemeContext.Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

So we created a ThemeContext with React.createContext and passed the default value as light. Now we can wrap all our application in ThemeContext.Provider and we can pass a value that we want here. This is the value that will be used instead of default value. Here we simple override it with light.

We didn't build any possibility to switch modes yet but we will do it later.

Now we can use useContext hook in any component to get access to other theme properties.

App.js

import React, { useState, useEffect, useContext } from "react";
import { ThemeContext } from "./index";

function App() {
  ...
  const theme = useContext(ThemeContext);
  ...

Now we can simply use all properties that we have in them inside any component. The most important part there is that you need to pass inside useContext the complete context. Not only ThemeContext.Provider or something else. Also every time when context value changes we will get update in all components and the all will rerender.

return (
  <div style=>
    React hooks for beginners
  </div>
);

So this is how we are using useContext but we can't really change a theme so let's implement this part now. For this we need to improve our ThemeContext.Provider. Because we want not only get the value from it but also a function that we can call in order to toggle a theme.

export const ThemeContext = React.createContext();
const ThemeContextProvider = ({ children }) => {
  const [theme, setTheme] = useState(themes.light);
  const [activeTheme, setActiveTheme] = useState("light");

  const toggleTheme = () => {
    const nextTheme = activeTheme === "light" ? "dark" : "light";
    setTheme(themes[nextTheme]);
    setActiveTheme(nextTheme);
  };
  return (
    <ThemeContext.Provider value={[theme, toggleTheme]}>
      {children}
    </ThemeContext.Provider>
  );
};

ReactDOM.render(
  <React.StrictMode>
    <ThemeContextProvider>
      <App />
    </ThemeContextProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

So here we created actually a component that returns ThemeContext.Provider. As you can see as a value we are giving theme and toggleTheme as an array to make the same approach like in hooks. As this is just a component we can use useState hook inside to manage state. If you didn't watch my useState hook, I will link it down in the description box below.

Now we can use our theme almost like a hook.

return (
  <div style=>
    <button onClick={toggleTheme}>Toggle theme</button>
    React hooks for beginners
  </div>
);

As you can see everything is working and we can toggle between theme and get theme data in all components.

Call to action

So context approach was working in React with classes already long time. useContext is just a hooks implementation for the same thing. What is also very important is the you can use Context with both classes and hooks. So if you project is a mix of both it's completely fine and you can reuse them.

If "React hooks for beginners" is too easy fr you I have a full hooks course which is going 8 hours where we are creating real application from scratch. I will link it down in the description below.

If you find this video helpful, don't forget to subscribe to this channel and hit subscribe button. Thanks for watching and I see you in my next video.

🚨 Important

📚 References