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 });
Props:
function Profile(props) {
return <h1>{props.user.name}</h1>;
}
Styles (as inline styles):
const style = { color: "red", fontSize: "20px" };
return <div style={style}>Hello</div>;
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:
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>;
}
}
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>;
}
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:
sayHello(); // Works fine
function sayHello() {
console.log("Hello");
}
Variables declared with var are hoisted but not initialized.
let and const are not initialized, leading to a temporal dead zone.
In React, hoisting matters if you:
Define helper functions below your component:
function MyComponent() {
return <div>{getGreeting()}</div>;
}
function getGreeting() {
return "Hello!";
}
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)