DEV Community

Cover image for ReactJS useContext Hook
athul jain
athul jain

Posted on

ReactJS useContext Hook

useContext() Hook

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

  • Step 1: Create Context Component
    eg:
    // MyContext.jsx
    import React,{ createContext } from “react”
    const MyContext = createContext();

    export default MyContext;

  • Step 1: Using Context Provider

eg:
// App.js
import React from 'react';
import MyContext from './MyContext';
import ChildComponent from './ChildComponent';

function App() {
const contextValue = {
name: 'John',
age: 30, };

return (





);
}

export default App;

  • Step 3: Using useContext hook eg:

// ChildComponent.js

import React, { useContext } from 'react';
import MyContext from './MyContext';

function ChildComponent() {
const context = useContext(MyContext);

return (


Name: {context.name}


Age: {context.age}



);
}
export default ChildComponent;

follow :

Top comments (1)

Collapse
 
lalami profile image
Salah Eddine Lalami

@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .

Here Article about : 🚀 Mastering Advanced Complex React useContext with useReducer ⭐ (Redux like Style) ⭐ : dev.to/idurar/mastering-advanced-c...


Mastering Advanced Complex React useContext with useReducer (Redux like Style)