Where should functions in function components go? 

By Bernie FitzGerald •  Updated: 03/12/22 •  1 min read

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.

Bernie FitzGerald

Keep Reading