Home > OS >  Component keeps re-rendering after state change
Component keeps re-rendering after state change

Time:07-13

I use handleMouseOver and handleMouseOut functions where I change the value of a state count. However, every time the state is changed the component re-renders instead of just the state. What am I missing here? Thanks.

function foo() {
  const [state, setState] = useState({ count: 0, data: {}});

  useEffect(() => {
    const getData = async () => {
      const response = await fetch(url);
      const data = await response.json();
      setState(prevState => ({
        ...prevState,
        data: data,
      }));

    };
    return ()=>{
      getData();
    }
  }, []);

  function handleMouseOver(e) {
    setState(prevState => ({
      ...prevState,
      count: e,
    })); 
  };

  function handleMouseLeave() {
    setState(prevState => ({
      ...prevState,
      count: null,
    }));  
  };  

  const { count, data } = state;

  const BlockComponent = () => {
    const data = data.arr;
    return (
      <Wrapper >
        {data.map((value, index) =>
          value.map((value, index) => {
            return (
              <Block 
                key={index} 
                val={value} 
                onm ouseEnter={e => handleMouseOver(value)} 
                onm ouseOut={handleMouseLeave}
              ></Block>
            );
          })
        )}
      </Wrapper>
    );
  };

  return (
    <Wrapper>
      <BlockComponent />
    </Wrapper>
  );
}

export default foo;

CodePudding user response:

React updates component if component state is changed. That's correct behaviour. I recommend you to learn react documentation, because component state is a basic concept.

CodePudding user response:

That's one of the main points of state -> component is rerendered when you change state.

CodePudding user response:

The Issue is with your handleMouseOver function. It is getting executed everytime there is a state Update and the same value is assigned to "count". All you have to do is place setState inside the condition that will compare the value of event received by the function and the current value of sate. It should be something like this.

function handleMouseOver(e) {
    if(count !== e){
    setState(prevState => ({
      ...prevState,
      count: e,
    })); 
    }
  };

  • Related