title: how, where, and when to best calculate a value to conditionally render react element
body: <p>i have a react form (.tsx) that i am making that pre-loads all of a user's account information and then allows them to make edits. i am using a functional component with hooks to handle state. i have a couple elements that will be conditionally rendered based on whether the form has been altered. overall, the isAltered method gets called three times per render. it seems it would be more efficient to calculate and hold the value once per render.  my question is - where, when, and how is the best way to calculate and store this value? </p>
  
  <p>the code that checks for changes: </p>
  
  <pre><code>  const isAltered = () =&gt; {
      const formValues = Object.keys(values).filter(k =&gt; k !== 'passwordConfirm');
  
      let i;
      for (i = 0; i &lt; formValues.length; i++) {
        let key = formValues[i];
        if (values[key] !== user[key]) {
          return true;
        } else {
          continue;
        }
      }
      return false;
    };
  </code></pre>
  
  <p>the react elements: </p>
  
  <pre><code>&lt;Button
    disabled={!isAltered()}
    className={classes.button}
    type="submit"
  /&gt;
  
  &lt;div className={`${isAltered() ? '' : classes.hideDisplay}`}&gt;
     &lt;TextField
         className={classes.textField}
         disabled={!isAltered()}
      /&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>i tried: </p>
  
  <pre><code>  let altered = false;
    useEffect(() =&gt; {
      altered = isAltered();
    }, [formValues]);
  </code></pre>
  
  <p>this doesn't work because the "altered" variable loses its value between renders and therefore isn't useful. so i tried storing "altered" in useRef as follows :</p>
  
  <pre><code>  let altered = React.useRef(false);
    useEffect(() =&gt; {
      altered = isAltered();
    }, [values]);
  </code></pre>
  
  <p>but now "altered" inside of useEffect returns me this error: </p>
  
  <blockquote>
    <p>Type 'boolean' is not assignable to type 'MutableRefObject'.></p>
  </blockquote>