Welcome to our comprehensive guide on the useContext hook in React JS! This tutorial is designed to help beginners and intermediate learners understand and master this powerful feature. Let's dive right in!
useContext?useContext is a React hook that allows you to share state and other data between components without having to pass props down manually. It simplifies the management of global state and makes your components more reusable and easier to understand.
To create a custom context, we first need to define a Context object.
import React, { createContext, useState } from 'react';
const MyContext = createContext();
function MyComponent() {
const [count, setCount] = useState(0);
return (
<MyContext.Provider value={{ count, setCount }}>
{/* Your component tree */}
</MyContext.Provider>
);
}
export { MyContext, MyComponent };In the example above, we create a custom context called MyContext and use the useState hook to manage the state. The component tree that uses this context will have access to the state through the value prop of the MyContext.Provider.
useContextTo use the context, we need to import the MyContext object and use the useContext hook in any component within the provider.
import React from 'react';
import { MyContext } from './MyComponent';
function Counter() {
const { count, setCount } = useContext(MyContext);
return (
<div>
Count: {count}
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}In the example above, we access the state (count and setCount) directly from the MyContext using the useContext hook.
In some cases, you might need to share state between unrelated components. For that, you can create nested contexts.
import React, { createContext, useState } from 'react';
const ThemeContext = createContext();
const CountContext = createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
<CountProvider value={0}>{children}</CountProvider>
</ThemeContext.Provider>
);
}
function CountProvider({ children, value }) {
const [count, setCount] = useState(value);
return (
<CountContext.Provider value={{ count, setCount }}>
{children}
</CountContext.Provider>
);
}
function Counter() {
const { count, setCount } = useContext(CountContext);
const { theme, setTheme } = useContext(ThemeContext);
return (
<div style={{ backgroundColor: theme === 'dark' ? '#333' : '#fff' }}>
Count: {count}
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}In the example above, we create two nested contexts (ThemeContext and CountContext) and use them in the Counter component.
createContext outside of any component.useContext hook in any component within the provider.What does the `useContext` hook do in React JS?
By the end of this tutorial, you should have a solid understanding of useContext and be able to apply it in your own projects. Happy coding! 🥳