I am trying to update a variable when the scores state changes. At the moment I have a function inside a useEffect hook which calculate the sum of the scores array and updates the global totalScore variable. For some reason the totalScore variable doesn't seem to be updating and displaying correctly on the screen - it just stays at 0.
let totalScore = 0
const [scores, setScores] = useState([])
useEffect(() => {
scores.forEach((score) => {
totalScore = score
}
}, [scores])
return (
<>
<p>{totalScore}</p>
</>
)
CodePudding user response:
Issue
For some reason the totalScore variable doesn't seem to be updating and displaying correctly on the screen - it just stays at 0.
This is because the useEffect hook runs after the component has rendered to the DOM. The totalScore variable was updated, but React needs another rerender to get it to the DOM.
Suggested Solution
Since it's derived "state" from the scores state, it would be better to just compute the totalScore from the scores state in the component render.
const [scores, setScores] = useState([]);
const totalScore = scores.reduce((total, score) => score total, 0);
return (
<>
<p>{totalScore}</p>
</>
);
You can memoize totalScore with the useMemo hook if necessary.
const totalScore = useMemo(() => {
return scores.reduce((total, score) => score total, 0);
}, [scores]);
CodePudding user response:
You need to have totalScore in your state for it to get updated.
const [totalScore, setTotalScore] = useState(0)
const [scores, setScores] = useState([])
useEffect(() => {
let ts = 0;
scores.forEach((score) => {
ts = score
}
setTotalScore(ts);
}, [scores])
