Function inside render and class in reactjs
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>
)
}
I think it's ultimately your choice, but I personally prefer only putting functions within render that deal exclusively with rendering components and/or JSX (i.e. mapping over a prop, switch statements that conditionally load a proper component based on a prop, etc...). If the logic behind the function is heavy, I'll leave it out of render.
Here's an example. Say in your component you have a "users" prop that is supposed to display a list of users. You might have a render function with these types of things:
render(){
// An array of user objects & a status string.
const { users, status } = this.props;
// Map users array to render your children:
const renderUserList = () => {
return users.map(user => {
return <div>{ user.firstName }</div>;
});
};
// Conditionally load a component:
const renderStatus = () => {
let component = '';
switch(status){
case 'loading':
component = <Component1 />
break;
case 'error':
component = <Component2 />
break;
case 'success':
component = <Component3 />
break;
default:
break;
}
return component;
}
// render() return:
return(
<div>
<div className="status">
{ renderStatus() }
</div>
<div className="user-list">
{ renderUserList() }
</div>
</div>
);
}
However, if you had a function that needed to somehow manipulate data about a user, it might be better to put that in a function outside of render.