I was trying to figure out how to fire a useEffect when its dependency is a useContext variable. My Context has an "update" variable, which at one point changes, but the effect isn't fired.
import { useEffect, useState, useContext } from "react"
import context from "./Context"
const Layout = () => {
const ctx = useContext(context)
const [updateState, setUpdateState] = useState(ctx.update)
useEffect(() => {
console.log("effect fired")
}, [updateState])
return (
<div>
</div>
)
}
export default Layout
I tested whether the issue was my context "update" variable not changing, but it does. I will appreciate any help with this.
CodePudding user response:
Your problem is that you used useState
. This in effect memoized/froze the value of updateState
, to the first run of this component.
You see useState
takes a single arg (default value). Which is only used on the first render of the component, to populate updateState
. When ctx.update
changes, useState
already has a default to set updateState
to, so it is ignored.
Instead, you can remove useState
completely...
import { useEffect, useState, useContext } from "react"
import context from "./Context"
const Layout = () => {
const { update as updateState } = useContext(context);
// Notice I have removed the useState.
useEffect(() => {
console.log("effect fired")
}, [updateState])
return (
<div>
</div>
)
}
export default Layout