DEV Community

P Mukila
P Mukila

Posted on

Today I learned-Object,this keyword and hoisting in react.js...

1.What is an Object in React.js?

In JavaScript (and React by extension), an object is a data structure used to store collections of data and more complex entities.

In React, objects are commonly used for:
Component state:

const [user, setUser] = useState({ name: "Alice", age: 30 });
Enter fullscreen mode Exit fullscreen mode

Props:

function Profile(props) {
  return <h1>{props.user.name}</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Styles (as inline styles):

const style = { color: "red", fontSize: "20px" };
return <div style={style}>Hello</div>;
Enter fullscreen mode Exit fullscreen mode

2.this Keyword in React.js
The this keyword refers to the context in which a function is executed.

In class components, this typically refers to the component instance:
Enter fullscreen mode Exit fullscreen mode

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    this.handleClick = this.handleClick.bind(this); // bind `this`
  }

  handleClick() {
    console.log(this.state.count); // `this` refers to the component
  }

  render() {
    return <button onClick={this.handleClick}>Click Me</button>;
  }
}
Enter fullscreen mode Exit fullscreen mode

If you don’t bind this, it might be undefined or refer to the wrong context.

In functional components with hooks, you don’t use this, which is one reason why hooks are popular:

function MyComponent() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    console.log(count);
  };

  return <button onClick={handleClick}>Click Me</button>;
}
Enter fullscreen mode Exit fullscreen mode

3.Hoisting in React.js
Hoisting is a JavaScript concept, not specific to React, but it still affects how you write React code.

In JavaScript:

    Function declarations are hoisted:
Enter fullscreen mode Exit fullscreen mode
sayHello(); // Works fine

function sayHello() {
  console.log("Hello");
}

Enter fullscreen mode Exit fullscreen mode
Variables declared with var are hoisted but not initialized.

let and const are not initialized, leading to a temporal dead zone.
Enter fullscreen mode Exit fullscreen mode

In React, hoisting matters if you:

Define helper functions below your component:
Enter fullscreen mode Exit fullscreen mode
function MyComponent() {
  return <div>{getGreeting()}</div>;
}

function getGreeting() {
  return "Hello!";
}
Enter fullscreen mode Exit fullscreen mode

Summary

Concept Meaning in React
Object Structure for storing and passing data (props, state)
this Refers to component instance in class components
Hoisting JS behavior affecting function and variable declaration order; important when defining helper functions

Top comments (0)