Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function inside render and class in reactjs

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.

like image 731
CraZyDroiD Avatar asked Mar 07 '17 10:03

CraZyDroiD


People also ask

Can we use function inside class in React JS?

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.

Can I write a function in render React?

Using JSX, you can create a function and return a set of JSX elements to a variable, and that variable used is to render the elements inside the render() function in React. This guide will help you learn how to return JSX to a variable and render JSX markups to the DOM.

Can we call function inside render?

In this article, we will learn how to call a function to render in ReactJS. React is having 2 types of components, i.e, Class based and Functional Components, but render method is only in Class based components. So we will make a class based component and call a function in that.

Can you use both functional and class components in React?

React lifecycle methods (for example, componentDidMount) cannot be used in functional components. React lifecycle methods can be used inside class components (for example, componentDidMount). Hooks can be easily used in functional components to make them Stateful.


2 Answers

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>
  )
}
like image 171
spirift Avatar answered Oct 05 '22 06:10

spirift


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.

like image 23
Nate Kimball Avatar answered Oct 05 '22 05:10

Nate Kimball