=
useContext
in React vs Provide/Inject in Vue
- React’s
useContext
is used to access shared data across the component tree without passing props down manually. - Vue’s
provide
andinject
do the same by letting parent components provide values that children can access without needing to pass props.
Example in Vue:
=
useContext in React vs. Provide/Inject in Vue
React’s useContext to share data across the component tree:
javascript
Copy code
import React, { createContext, useContext } from 'react';
const MyContext = createContext("Hello from Context");
function Parent() {
return (
<MyContext.Provider value="Hello from Parent">
<Child />
</MyContext.Provider>
);
}
function Child() {
const sharedData = useContext(MyContext);
return <p>{sharedData}</p>; // Outputs: "Hello from Parent"
}
Vue equivalent:
javascript
Copy code
// Parent Component
export default {
provide() {
return {
sharedData: "Hello from Parent"
};
}
}
// Child Component
export default {
inject: ["sharedData"],
mounted() {
console.log(this.sharedData); // "Hello from Parent"
}
}
=
No comments:
Post a Comment