Home > Enterprise >  React component is updating late
React component is updating late

Time:11-13

I am using React.useEffect() and the results are updating late. Why is that so ?

function Process(props) {
  const [results, setResults] = React.useState({
    number: "",
    f: {}
  });

  let data = props.data; //returns object from another component which changes

  React.useEffect(() => {
    return () => setResults(data)
  }, [data]);

  return (
    <p>{results.number}</p> //ouputs previous number
  );
};

Please tell me if you need the component which passes the props={data} to Process() component.

Thanks

CodePudding user response:

if props.data is already a useState there is no need for using another useEffect and useState, React already handles that and you can just use the value

function Process(props) {
   let data = props.data;

  return <p> { data.number } </p>
}

CodePudding user response:

the return value of a useEffect function is a function that get's called to clean what the useEffect does

if you want to run the setResults as soon as data change, do that in the body of the function

React.useEffect(() => {
  setResults(data)
}, [data]);

https://reactjs.org/docs/hooks-effect.html

  • Related