• Introduction It’s time to learn about useContext in React Hooks! The useContext Hook allows you to access the values of a context without using the traditional context consumers. Join Geek and Gal as they explore useContext together.
Gal Normal

The useContext Hook is super useful for accessing context values without wrapping your components in context consumers!

Geek Curious

Oh, that sounds handy! How do you use it?

Gal Happy

First, you'll need a context. You can create one using React.createContext() . Then, import the useContext Hook from React and use it with your context.

  • Creating a Context and Using useContext
Gal Pleased

Here's an example of creating a context and using useContext to access its value:

import React, { useContext } from 'react';

// Creating a context
const ThemeContext = React.createContext('light');

function ThemedButton() {
  // Using useContext to access the context value
  const theme = useContext(ThemeContext);
  return <button className={theme}>I'm a {theme} button!</button>;
}
Geek Happy

So, you create a context with React.createContext() and then use useContext with that context to get its value!

Gal Happy

Exactly! And you can use the context value however you want in your component!

  • Providing Context Value
Gal Pleased

But remember, you'll still need a context provider to set the context value. You can use the Provider component from your context for that!

import React from 'react';
import ThemedButton from './ThemedButton';

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}
Geek Happy

Ah, so the context provider sets the value for the context, and useContext allows components to access that value!

Gal Happy

You got it! useContext makes it easier to access context values in your functional components without the extra nesting!

  • Conclusion useContext is a powerful React Hook that simplifies accessing context values in functional components. By using useContext, you can avoid unnecessary nesting and make your code cleaner and more efficient. Happy coding with useContext! 😃