0

if ProjectItem don't have to reuse anywhere, where is the difference?

and what if i put declare component inside a loop, does it consume lots of memory?

1

const ProjectItem = ({ _id, title }) => {
  return <div key={_id}>
    <a href={`/projects/${_id}`}>{title}</a>
  </div>
}

class view extends Component {
  render() {
    const { ready, projects } = this.props

    if (!ready)
      return <LoadingView />

    return projects.map((project, projectIdx) => <ProjectItem key={projectIdx} {...project} />)
  }
}

2

class view extends Component {
  render() {
    const { ready, projects } = this.props

    if (!ready)
      return <LoadingView />

    const ProjectItem = ({ _id, title }) => {
      return <div key={_id}>
        <a href={`/projects/${_id}`}>{title}</a>
      </div>
    }

    return projects.map((project, projectIdx) => <ProjectItem key={projectIdx} {...project} />)
  }
}

3

class view extends Component {
  render() {
    const { ready, projects } = this.props

    if (!ready)
      return <LoadingView />

    return projects.map((project, projectIdx) => <ProjectItem key={projectIdx} {...project} />)

    function ProjectItem({ _id, title }) {
      return <div key={_id}>
        <a href={`/projects/${_id}`}>{title}</a>
      </div>
    }
  }
}
crapthings
  • 2,485
  • 3
  • 20
  • 33

2 Answers2

1

In terms of performance they are all the same.

I would not use 3 though as this syntax is not considered outdated.

klugjo
  • 19,422
  • 8
  • 57
  • 75
1

Method 1 vs 2.3

For second and third declaration, because you put declare component at render function, it will create again when render is called.

So first one is better, you just declare this component once.

Method 2 vs 3

Basically, both are the same.

The different is the third method is you declare function after calling it. Because of function hoisting property, this will work in javascript, but in some lint or styleguide, they don't suggest this pattern.

I paste another question is discussing declare var function or function:

var functionName = function() {} vs function functionName() {}

Chen-Tai
  • 3,435
  • 3
  • 21
  • 34