Where should functions in function components go? 

It is technically possible to define functions inside functional components as in the following example:

function App() {
  let test;
  
  function myInsideFunction() {
    test = "TEST";
  }
 
  myInsideFunction();

  return (
    <div>
      This is a working {test} component 
    </div>
  )
}

The main issue with the above example is that myInsideFunction is going to be defined every time the App component is rendered.

To avoid this re-rendering you can just refactor myInsideFunction to be outside of the component like this:

function myInsideFunction() {
  return "TEST";
}

function App() {
  let test;
    
  test = myInsideFunction();

  return (
    <div>
      This is a working {test} component 
    </div>
  )
}

If the myInsideFunction function had functionality that was useful outside of the App component then this would help as any component would now have access to the function.

Where should functions in function components go? 

Leave a Reply

Your email address will not be published.

Scroll to top