skip to Main Content

Thank you all in advance for your help.
I am not sure why when i updated the percentageDone state in my loadDataFunction() will update the RenderData1Component where it shouldn’t. Shouldn’t it update only when data1 changed?

I have a piece of code like this.

  const [loading, setLoading] = useState(true);
  const [data1, setData1] = useState(null);
  const [percentageDone, setPercentageDone] = useState(0);


  LoadDataFunction(){
    // calling multiple apis (let say 10) in a promise and call setPercentageDone() whenever 1 of the Apis is done.
  }
  useEffect( () => {
     LoadDataFunction()
  },[])
  useEffect( () => {
     if (condition are met) {
       LoadDataFunction() // Reload Data All over again for latest data
     }
  }, [condition])

  return (
    loading ? percentageDone
            : <RenderData1Component data={data1}>
  )

I want to update <RenderData1Component data={data1}> only when i updated data1 state not percentageDone. but whenever i am updating setPercentageDone() it also trigger a re-render for <RenderData1Component data={data1}>

2

Answers


  1. Chosen as BEST ANSWER

    Thanks all for the help.

    I found the problem. The problem came from the <RenderData1Component/> itself. The theme code get's run every time when the state updated and it updated the css class for that CustomSwitch element which causes the re-render.

    My solution is to move the custom switch outside of this component and make it an external component.

    import { styled } from '@mui/material/styles';
    import Switch from '@mui/material/Switch';
    const CustomSwitch = styled(Switch)(({ theme }) => ({.........}) //Cause of re-render
    

  2. I’m not sure, but this may help you.

    const [loading, setLoading] = useState(true);
    const [data1, setData1] = useState(null);
    const [percentageDone, setPercentageDone] = useState(0);
    
    const loadDataFunction = async () => {
      // Perform API calls and update percentageDone
    };
    
    useEffect(() => {
      loadDataFunction().then(() => {
        setLoading(false);
      });
    }, []);
    
    useEffect(() => {
      if (condition) {
        setLoading(true);
        loadDataFunction().then(() => {
          setLoading(false);
        });
      }
    }, [condition]);
    
    return (
      loading ? (
        <div>{percentageDone}% Loading...</div>
      ) : (
        <RenderData1Component data={data1} />
      )
    );
    

    It may be possible that you’re giving multiple conditions, which may be causing problems. Check it as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search