Search code examples
javascriptreactjsreact-props

Updating state repeatedly - ReactJs


Hi I have a parent component, having two child component as follows, Child1 has draggable div element, which on drag gives value out to Parent component which then I have to pass to Child2 and utilise, but before utilising it in Child2 I have to make a dozens of calculations.

const Parent = () => {
  const [dragValue, setDragValue] = useState(0);
  const dragHanlder = (dragVal) => {
     setDragValue(dragVal);
  };
  return (
        <Child1 mouseDrag={dragHanlder} />
        <Child2 dragValue={dragValue}/>
  );
}

class Child2 extends React.Component {
   state = {
     afterCalculationsVal: 0
   };
   componentDidUpdate = () => {
      const { dragValue } = this.props;
      const someFinalval = val //this val takes dragValue applies checks, calculations and conditions and finally gives out some value
      this.setState({afterCalculationsVal: someFinalval });
   };

   render() {
      const { afterCalculationsVal } = this.state;
      return (
         <Child3 afterCalculationsVal={afterCalculationsVal} >
      );
   }
}

Problem is I'm getting maximum depth reached issue, because I'm setting state for drag which is continuous. Is there any way I can overcome this. I cannot use the 'dragValue' coming in props in Child2 directly, the calculations on the props value is mandatory, and I have to set state after that.


Solution

  • The problem is that when the component updates it is going into componentDidUpdate then setting state causing another update. Setting an if condition checking drag value should fix your problem.

    componentDidUpdate = (prevProps, prevState) => {
        const { dragValue } = this.props;
        if(prevState.dragValue !== prevState.dragValue){
          // Will only re-render when dragValue changes
          const someFinalval = val 
          this.setState({afterCalculationsVal: someFinalval });
        }
      };