Search code examples
javascriptreactjsuse-effectuse-state

React component is updating late


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


Solution

  • 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