React functions inside render ()

Is there any preference for where you put functions inside the react component. I am still involved in the training, so I’m just trying to figure out the best practices.

class Content extends React.Component { /// Whats the difference between putting functions here such as Hello(){ } render(){ /// or here Hello(){ } return()( <div>blah blah </div> ) } } 
+5
source share
1 answer

A rendering function will be created in the rendering method, which is a small performance hit. This is also messy if you put them in a render, which is a much more serious reason, you don't need to scroll through the code in the render to see the html output. Always put them on the class.

For stateless components, it is best to save functions outside the main function and instead pass them in the details, otherwise a function will be created for each rendering. I have not tested the performance, so I do not know if this is micro-optimization, but it is worth noting.

Example:

 const MyStatelessComponent = ({randomProp}) => ( render() { doSomething(randomProp); return <div /> } ); doSomething = (randomProp) => { //Do something here } 
+21
source

Source: https://habr.com/ru/post/1261999/


All Articles