'THIS' causes double Undefined in react functional component!! why??

'THIS' causes double Undefined in react functional component!! why??

Table of contents

No heading

No headings in the article.

The infamous "double undefined" issue!

This is a common gotcha in React, and it's not specific to your code. It's related to how React handles the this context in functional components.

In a functional component, this is not bound to the component instance, unlike in class components. Instead, this refers to the global object (usually the window object in a browser).

When you use console.log(this) inside a functional component, React will execute the console.log statement twice:

  1. During the render phase: When React is rendering the component, it will execute the console.log statement. At this point, this is undefined because the component instance hasn't been created yet.

  2. During the commit phase: After the component has been rendered, React will execute the console.log statement again. This time, this is still undefined because the component instance is not accessible in a functional component.

This double execution is due to React's rendering mechanism, which involves two phases:

  1. Render: React generates the virtual DOM and executes the component's render method (or the functional component's body).

  2. Commit: React updates the actual DOM with the changes from the virtual DOM.

Alternatively, if you need to access the component instance, consider using a class component or a library like react-hooks that provides a way to access the component instance in functional components.