title: React hooks : how can I update a state within useEffect when the state itself is the dependency?
body: <p>I know there already are already some related questions, like <a href="https://stackoverflow.com/questions/62979323/how-can-react-useeffect-watch-and-update-state">How can React useEffect watch and update state?</a>, but still, I don't get it totally.</p>
  <p>Let's say I set an <code>index</code> state based on a prop; and I need to sanitize that value anytime it is set.</p>
  <pre><code>&lt;MyComponent index={4}/&gt;
  </code></pre>
  <p>This is how I attempted to do it:</p>
  <pre><code>useEffect(() =&gt; {
    setIndex(props.index);
  }, [props.index]);
  
  useEffect(() =&gt; {
    const sanitized = sanitizeIndex(index);
    setIndex(sanitized);
  },[index])
  
  const sanitizeIndex = index =&gt; {
      //check that index exists in array...
      //use fallback if not...
      //etc.
      return index
  }
  </code></pre>
  <p>It does not work (infinite loop), since the state is watched <strong>and</strong> updated by the second <code>useEffect()</code>.</p>
  <p>Of course, I could avoid this by calling <code>sanitizeIndex()</code> on the prop, so I only need a single instance of <code>useEffect()</code>:</p>
  <pre><code>useEffect(() =&gt; {
    setIndex(sanitizeIndex(props.index));
  }, [props.index]);
  </code></pre>
  <p>Thing is, I call <code>setIndex</code> plenty of times in my code, and I fear to miss using <code>sanitizeIndex</code>.</p>
  <p>Is there another way to &quot;catch&quot; and update a state value being set ?</p>
  <p>Thanks !</p>