Abrar
Abrar

Reputation: 7222

How to consider defining a functional component inside a class component and outside the class in React?

Considering the following three places of defining a functional component in React -

  1. Inside a class (outside the render method)
  2. Inside a class (inside the render method)
  3. Outside the class

In the sample code below, funcComponent1, funcComponent2 and funcComponent3 are defined in the three different locations. How do I consider when to define a functional component in any of these 3 places?

import React, { Component } from 'react';


const FuncComponent1 = (props) => {
  return (
    <p>{props.name}</p>
  )
}

class TestComponent extends Component {

  constructor(props){
    super(props);
    this.state = {
      name: "JavaScript"
    }
  }


  FuncComponent2 = (text) => {
    return (
      <p>{text}, {this.state.name}</p>
    )
  }


  render(){

    const FuncComponent3 = (props) => {
      return (
        <p>{props.text}, {this.state.name}</p>
      )
    }

    return (
      <div>
        <FuncComponent1 name={'Abrar'} text={'Hello World'}/>
        <FuncComponent3 text={"HEllo World"}/>
      </div>
    )
  }

}

export default TestComponent;

Upvotes: 3

Views: 3678

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

You must avoid using functional component inside of render since they will be recreated on every render.

As far as using functions that return JSX inside Class component but outside render` is considered, you can do that when you want to make use of the state or props of the class in order to render JSX content but that which is very specific to the particular class

A functional component outside of React component is most advantageous when the same component can be used at multiple places and hence it makes sense to pass props to it and render it.

Upvotes: 8

Related Questions