Home > other >  Functional component not rerendering, even passing [sum] in useEffect dependency as it changes
Functional component not rerendering, even passing [sum] in useEffect dependency as it changes

Time:12-26

Even on click of button, the sum variable changes to 29.98, but though I am using useEffect hook, and I've added dependency as [sum], so that if value of num changes let sum = 0, as I click button, and sum now becomes as 29.98, so re-render should happen and I should now see updated value on UI, but it still shows 0, I think component does not Rerender. Why?

import React, { useEffect } from 'react'; 
import './SelectEx1.css'

const SelectEx1 = (props) => {

let data = [
    {
        id: 1,
        title: "Milk",
        price: 15.99,
    },
    {
        id: 2,
        title: "Bread",
        price: 13.99,
    },
];
let sum = 0; 

useEffect(()=>{}, [sum]);

const handleClick = () => {
  console.log(data);
  data.map((item) => {
    sum = (sum   item.price)
  });
}

  return (
    <div>
      <p>hello, {sum}</p>
      <button onClick={handleClick}>click-me</button>
    </div>
  )
}
export default SelectEx1; 

CodePudding user response:

I think what you want is

const [sum, setSum] = useState(0); 
...
const handleClick = () => {
  console.log(data);
  const total = data.reduce((a, b) => a   b, 0);
  setSum(total);
}

So that handleClick will trigger a change in state, which triggers rerender. Putting sum into the dependency list of useEffect merely triggers the function(first parameter) in useEffect when sum is changed. Since the first paramter is an empty function, it does nothing when sum is changed.

CodePudding user response:

Try this:

import React, { useEffect } from 'react'; 
import './SelectEx1.css'

const data = [
    {
        id: 1,
        title: "Milk",
        price: 15.99,
    },
    {
        id: 2,
        title: "Bread",
        price: 13.99,
    },
];
 
const SelectEx1 = (props) => {

const [sum, setSum] = React.useState(0)

const handleClick = () => {
  const total = data?.reduce(function (previousValue, currentValue) {
    return previousValue   currentValue.price
  }, 0)
  setSum(total)
}

  return (
    <div>
      <p>hello, {sum}</p>
      <button onClick={handleClick}>click-me</button>
    </div>
  )
}

CodePudding user response:

You don't need useEffect, put sum in useState and change onClick like below:

const [sum,setSum] = useState(0);
const handleClick = () => {
  const reducer = (previousValue, currentValue) => previousValue.price   
  currentValue.price;
  setSum(data.reduce(reducer))
}
  • Related