'How to checddsa hooks?

I need to detect every change of variable state BUT check code:

  useEffect(() => {  
    if (value) {
        setSelect(value); 
    }
  }, [value]);

code above checkin every second and i got error:

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

I need to check only when value is changed not every second!

value is props data from parent component.

const OrganisationUnitInput = ({ 
  input
}) => {
  const [showModal, setShowModal] = useState(false);

  const value = input.value || [];

 

const value = input.value || [];

  const handleChange = useCallback(
    (value) => {
      input.onChange(value);
      setShowModal(false);
    },
    [input]
  );
    }


Solution 1:[1]

It is happening because you are setting value state and passing same value as dependency array . which results in re rendering

Solution 2:[2]

You misunderstood the useEffect hook, when you pass the second argument with some variable you are telling to react that the function of the effect must be executed if the variable change.

So in your code You are making an infinity loop.

To detect the change on the var only pass the var in the array and your function will be executed if any change occurred.

const Comp = () => {
    const [value, setValue] = useState(0)

    useEffect(() => {
        // This code will be execute any time that the var value
        // change

        console.log("The value change, now is: ", value)

        // so if you change the var here your will cause another call
        // to this effect.
    }, [value])
    
    return <button onClick={() => { setValue(prev => prev + 1) }}>
        Change Value
    </button>
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shrinidhi Batavi
Solution 2 Gytree