How to use context in React.js



Image not found!!

In React.js, managing and utilizing context is a powerful way to share values like themes, authentication status, or any other global state across components without the need to pass props manually through every level of the component tree.

Here's a basic guide on how to use context in React:

1. Create a Context

jsx
// context.js import { createContext } from 'react'; const MyContext = createContext(); export default MyContext;

2. Provide a Context value

Wrap your component tree with a Provider to supply the context value.

jsx
// App.js import React from 'react'; import MyContext from './context'; const App = () => { const contextValue = { // Your context data goes here data: 'Hello from context!', }; return ( <MyContext.Provider value={contextValue}> {/* The rest of your components */} </MyContext.Provider> ); }; export default App;

3. Consume the Context

Use the useContext hook to consume the context in your components.

jsx
// SomeComponent.js import React, { useContext } from 'react'; import MyContext from './context'; const SomeComponent = () => { const contextValue = useContext(MyContext); return ( <div> <p>{contextValue.data}</p> </div> ); }; export default SomeComponent;

Note:

  • The Provider should wrap the components that need access to the context.
  • useContext is used to access the current context value.
  • If you need to provide multiple values, you can pass an object as the context value.

Example:

jsx
// context.js import { createContext } from 'react'; const MyContext = createContext(); export default MyContext;
jsx
// App.js import React from 'react'; import MyContext from './context'; import SomeComponent from './SomeComponent'; const App = () => { const contextValue = { data: 'Hello from context!', theme: 'light', // other values... }; return ( <MyContext.Provider value={contextValue}> <SomeComponent /> </MyContext.Provider> ); }; export default App;
jsx
// SomeComponent.js import React, { useContext } from 'react'; import MyContext from './context'; const SomeComponent = () => { const contextValue = useContext(MyContext); return ( <div> <p>{contextValue.data}</p> <p>{contextValue.theme}</p> </div> ); }; export default SomeComponent;

This way, SomeComponent can access values from the context without having to pass them down through props.