I have two components app.js and posts.js.
My app.js component
import React, { createContext, useState } from 'react'
import Posts from './components/Posts'
const val = createContext()
const App = () => {
const msg = 'hi'
return (
<div>
<val.Provider value={msg}>
<Posts />
</val.Provider>
</div>
)
}
export default App
export { val }
My Posts.js component
import React from 'react'
import { val } from '../App'
import { useContext } from 'react'
const Posts = () => {
const greet = useContext(val)
return <div>{greet}</div>
}
export default Posts
I want to update the msg from 'hi' to let say 'hello' from Posts component but I don't know how it can be done can someone plz help me understand that including the flow of how values get changed ? I Thanks
CodePudding user response:
msg
needs to be state:
const App = () => {
const state = useState('hi')
return (
<div>
<val.Provider value={state}>
<Posts />
</val.Provider>
</div>
)
}
and then:
const Posts = () => {
const [greet,setGreet] = useContext(val)
return (
<>
<div>{greet}</div>
<button onClick={() => setGreet('hello')}>Change to hello</button>
</>
)
}
It's helpful to look at context as just a prop from far above that you don't want to keep passing down. It's helpful, because that's all that it is.
A reason to use context instead of a prop:
You've got to pass it down through a lot of components, some of which really don't have anything to do with that prop
A reason not to use context:
You're tightly coupling your component to that context.
It's up to you to decide if the tradeoffs of tight coupling are worth it. Sometimes they are, sometimes they aren't. No hard and fast rules.