Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to learn reactjs and i have some uncertainties. I was refering react DOCS and some other tutorials and i saw functions are written inside render function and also inside class. What things should we do inside render function in react?

1st way

class App extends Component {

    test(user) {

        return user.firstName;
    }

    render() {

        const user = {
            firstName: 'Harper',
            lastName: 'Perez'
        };

        return (

            <div>

                <h1>{this.test(user)}</h1>

            </div>
        )
    }
}

2nd way

class App extends Component {

       render() {

        const user = {
            firstName: 'Harper',
            lastName: 'Perez'
        };

        function test(user) {

            return user.firstName;
        }

        return (

            <div>

                <h1>{test(user)}</h1>

            </div>

        )

    }
}

Both this methods work. But i want to know what is the best method to do this? Most importantly i want to know what kind of things i can do inside render function.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

The render method normally gets called a lot of times. I think it is more performant to declare your functions outside of the render method if you can. See this answer for a more detailed explanation of the render method.

The test function in your example is a pure function, this allows you to declare it outside the scope/context of the react component altogether as it only needs access to the arguments that are passed in.

That said, it's perfectly fine to declare functions inside a render method or more commonly these days a functional component. There are hooks like useCallback that can help with performance but 99% of the time it's not an issue. Always remember that premature performance optimisation is the roof of all evil and you need to measure performance before you can improve it.

// helpers.js
const test = function(user) {
    return user.firstName;
}

// App.js
const App = () => {
  const user = {
    firstName: 'Harper',
    lastName: 'Perez'
  }

  return (
    <div>
      <h1>hello {test(user)}</h1>
    </div>
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...