Open In App

How does useContext help with sharing data between components in React?

useContext is a hook in React that facilitates the sharing of data between components without the need to pass props manually through every level of the component tree. It allows components to consume data from a context that has been defined higher up in the component hierarchy.

How does it work?

useContext promotes a more efficient and scalable way to share data between components by providing a simple and intuitive API for accessing shared values within the React context.



Example: Below is the example that sharing data between component in React with help of useContext.




// App.js
 
import React from 'react';
import AnotherComponent from './AnotherComponent';
import ThemedComponent from './ThemeComponent';
import ThemeProvider from './ThemeProvider';
 
const App = () => {
    return (
        <ThemeProvider>
            <ThemedComponent />
            <AnotherComponent />
        </ThemeProvider>
    );
};
 
export default App;




// ThemeContext.js
 
import React, { createContext } from 'react';
 
const ThemeContext = createContext();
 
export default ThemeContext;




// ThemeProvider.js
 
import React, { useState } from 'react';
import ThemeContext from './ThemeContext';
 
const ThemeProvider = ({ children }) => {
    const [theme, setTheme] = useState('light');
 
    return (
        <ThemeContext.Provider
            value={{ theme, setTheme }}>
            {children}
        </ThemeContext.Provider>
    );
};
 
export default ThemeProvider;




// ThemedComponenet.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
 
const ThemedComponent = () => {
    const { theme, setTheme } = useContext(ThemeContext);
 
    const toggleTheme = () => {
        setTheme(theme === 'light' ? 'dark' : 'light');
    };
 
    return (
        <div style={{
            backgroundColor: theme === 'dark' ?
                'black' : 'white', color: theme === 'dark' ?
                    'white' : 'black'
        }}>
            <p>Current theme: {theme}</p>
            <button onClick={toggleTheme}>
                Toggle Theme
            </button>
        </div>
    );
};
 
export default ThemedComponent;




// AnotherComponet.js
import React, { useContext } from 'react';
import ThemeContext from './ThemeContext';
 
const AnotherComponent = () => {
    const { theme } = useContext(ThemeContext);
 
    return (
        <div>
            <p>This component also knows
                the current theme: {theme}
            </p>
        </div>
    );
};
 
export default AnotherComponent;

Output:



Output


Article Tags :