- 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.
- Creating a Context and Using useContext
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>;
}
- Providing Context Value
import React from 'react';
import ThemedButton from './ThemedButton';
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedButton />
</ThemeContext.Provider>
);
}
- 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! 😃