react difference between class method and file global function?

Viewed 89

case 1: file scope global function

// test.tsx

const someFunction = (text) => {
    console.log(text)
}

class SomeComponent extends React.Component {
    constructor(props){
        super(props)
        someFunction("Hello World!")
    }

}

case 2: class method

// test2.tsx
class SomeComponent extends React.Component {
    constructor(props){
        super(props)
        this.someFunction("Hello World!")
    }

    someFunction(text){
        console.log(text)
    }
}

in functional component, functions are recreated every render so you optimize it using useCallback but as far as I know, this is not the case for class component's methods.

Is there any difference in 2 approaches except that someFunction in case 1 can't access this?

1 Answers

I think it's ultimately your choice, but I personally prefer only putting functions within class so that whenever i inherit a class all functions can be used in another class (p.s it doesn't really matter)

like this

class SomeComponent extends React.Component {
    helloWorld(number){
      return number + 2;
  }


}

and

class AnotherComponent extends SomeComponent {
    render(){
      <div onClick ={()=>{
        helloWorld(10)}}>
      </div>
  }
}

in another hand you can export function directly if define them outside of class

export const someFunction = (text) => {
    console.log(text)
}

class SomeComponent extends React.Component {
    constructor(props){
        super(props)
        someFunction("Hello World!")
    }

}
Related