Context in React JS

 Context in React JS


Context is a way to share data between components without having to pass it through props. Here's an example of how to use the createContext and useContext functions to share data between components:

jsx


import React, { createContext, useContext } from 'react';


const MyContext = createContext('default value');


function ChildComponent() {

  const contextValue = useContext(MyContext);

  return <p>The context value is: {contextValue}</p>;

}


function ParentComponent() {

  return (

    <MyContext.Provider value="hello world">

      <ChildComponent />

    </MyContext.Provider>

  );

}


ReactDOM.render(<ParentComponent />, document.getElementById('root'));

In this example, the createContext function is used to create a new context called MyContext with an initial value of 'default value'.


The ChildComponent function uses the useContext hook to access the current value of MyContext. The ParentComponent function provides a new value for MyContext by wrapping the ChildComponent component in a MyContext.Provider component.


When the ChildComponent function is rendered, it will display the current value of MyContext, which in this case is 'hello world'.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...