I have a functional component with a stateful value that is based on a prop from Context, and when i update my Context value, the stateful value is not also updated.
export default function PomoTimer() {
const { state } = useContext(AppContext)
const { pomodoroDuration } = state
const [timeLeft, setTimeLeft] = useState(pomodoroDuration)
console.log('pomoDuration', pomodoroDuration)
console.log('timeLeft', timeLeft)
...
}
Here when I update PomodoroDuration from the Context, the timeLeft stateful value is not equal to the new PomodoroDuration. I want the "timeLeft" value to be always updated and equal to the new pomodoroDuration when I update it, how can I do it?
When i change my Context.pomoDuration to a new value, this is logged:
pomoDuration 30
timeLeft 50
However i am initializing my timeLeft stateful value with the pomoDuration value const [timeLeft, setTimeLeft] = useState(pomodoroDuration)
, so I don't really understand what is happening here. Thanks !
State is only ever instantiated once, when the component mounts. If you want to update the timeLeft
state when the context updates then use an effect with a dependency on pomodoroDuration
for that. If you are familiar with class-based components then an useEffect
hook with dependency is equivalent to componentDidUpdate
.
export default function PomoTimer() {
const { state } = useContext(AppContext);
const { pomodoroDuration } = state;
const [timeLeft, setTimeLeft] = useState(pomodoroDuration);
useEffect(() => {
setTimeLeft(pomodoroDuration);
}, [pomodoroDuration]);
...
}
Side note: Don't console log state updates in the body of functional components, you should also use an effect for that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.