Place data and logic inside or outside React components?

Viewed 822

I learn react, and I dont understand what is the difference between placing data or function inside or outside function components ?

What is the best practice, and when use the first or second example ?

  • Declare in component :
import React from 'react'

const SomeComponent = () => {
  const list = ['foo', 'bar']

  function add(foo) {
    return foo + 1
  }

  // other logics...

  return (
    // list...
  )
}
  • Declare outside the component :
import React from 'react'

const list = ['foo', 'bar']

function add(foo) {
  return foo + 1
}

const SomeComponent = () => {
  // other logics...

  return (
    // list...
  )
}

Have a nice day :)

3 Answers

If your function is a pure function that is not accessing the component's context, you can just put it outside of the component.

It doesn't matter in that case.

But when you need to use this inside the function, it's necessary to define it inside the component.

This post could be helpful too.

Functions in stateless components?

I think the 2nd option is a better cause when react re-renders the "SomeComponent", it doesn't have to create foo() again and again.

If you don't want to use class components like state and other methods than declare outside component else inside the component. In inside component call function as this.functionName

Related