title: React Hooks: accessing state across functions without changing event handler function references
body: <p>In a class based React component I do something like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>class SomeComponent extends React.Component{
      onChange(ev){
          this.setState({text: ev.currentValue.text});
      }
      transformText(){
          return this.state.text.toUpperCase();
      }
      render(){
          return (
              &lt;input type="text" onChange={this.onChange} value={this.transformText()} /&gt;
          );
      }
  }
  </code></pre>
  
  <p>This is a bit of a contrived example to simplify my point. What I essentially want to do is maintain a constant reference to the onChange function. In the above example, when React re-renders my component, it will not re-render the input if the input value has not changed.</p>
  
  <p>Important things to note here:</p>
  
  <ol>
  <li>this.onChange is a constant reference to the same function.</li>
  <li>this.onChange needs to be able to access the state setter (in this case this.setState)</li>
  </ol>
  
  <p>Now if I were to rewrite this component using hooks:</p>
  
  <pre class="lang-js prettyprint-override"><code>function onChange(setText, ev) {
      setText(ev.currentValue.text);
  };
  
  function transformText(text) {
      return text.toUpperCase();
  };
  
  function SomeComponent(props) {
      const [text, setText] = useState('');
  
      return (
          &lt;input type="text" onChange={onChange} value={transformText()} /&gt;
      );
  }
  </code></pre>
  
  <p>The problem now is that I need to pass <code>text</code> to <code>transformText</code> and <code>setText</code> to <code>onChange</code> methods respectively. The possible solutions I can think of are:</p>
  
  <ol>
  <li>Define the functions inside the component function, and use closures to pass the value along.</li>
  <li>Inside the component function, bind the value to the methods and then use the bound methods.</li>
  </ol>
  
  <p>Doing either of these will change the constant reference to the functions that I need to maintain in order to not have the <code>input</code> component re-render. How do I do this with hooks? Is it even possible?</p>
  
  <p>Please note that this is a very simplified, contrived example. My actual use case is pretty complex, and I absolutely don't want to re-render components unnecessarily.</p>
  
  <p>Edit:
  This is not a duplicate of <a href="https://stackoverflow.com/questions/53159301/what-usecallback-do-in-react">What useCallback do in React?</a> because I'm trying to figure out how to achieve a similar effect to what used to be done in the class component way, and while <code>useCallback</code> provides <em>a</em> way of doing it, it's not ideal for maintainability concerns.</p>