Amar
Amar

Reputation: 145

Rendering component in React shows flicker

Can anyone explain to me the main difference between rendering a JSX Component as a function and as a Tag. The achieved result is the same but somehow if I render JSX component like <Display/> show a flicker on the screen but rendering the component like {Display()} work absolutely fine. For both the cases, the component is re-render.

Note: I am navigating between the page and every time I navigate back to the screens, I'm re-rendering it intentionally to update the previous screen.

const App = ()=> {
  const Display = ()=>{
   console.log(" === Rendering display ===")
   return (
     <h1> Hello there.. </h1>
   )

  return(
  <div>
    <Display/>
    {Display()}
  </div>

}

Upvotes: 5

Views: 12658

Answers (1)

ltroller
ltroller

Reputation: 181

The reason this is happening is that you are defining your component Display from within another component (in this case App).

This is an anti-pattern, as the component will be redefined on every render of its parent component.

The correct way would be to define these components separately:

const Display = ()=> {
 console.log(" === Rendering display ===")
 return (
   <h1> Hello there.. </h1>
 );
}

const App = () => {
  return(
  <div>
    <Display/>
    {Display()}
  </div>
  )
}

As to the difference between both methods, here is a summary taken from an article posted by Kent C. Dodds on the subject:

React doesn't know the difference between us calling a function in our JSX and inlining it. So it cannot associate anything to the Counter function, because it's not being rendered like a component.

Upvotes: 9

Related Questions