1)What is the difference between a functional component and a class component in React?
- In React, both functional components and class components are used to build user interfaces, but they differ in how they are written and how they handle state and lifecycle methods.
- A functional component is simply a JavaScript function that returns JSX, and with the introduction of hooks like useState and useEffect, it can now handle state and side effects in a clean and concise way.
- A class component is created using ES6 classes **and **extends React. Component, where state is managed using this.state and updated with this.setState(). Class components also rely on built-in lifecycle methods such as componentDidMount and componentWillUnmount.
- Functional components are generally shorter, easier to read, and are the modern standard in React development, while class components are more verbose and are mostly found in older codebases.
2)How does JSX work internally? Why do we need it instead of plain JavaScript?
- JavaScript XML, is a syntax extension used in React that allows developers to write HTML-like code inside JavaScript. Internally, JSX is not understood by browsers; instead, it gets compiled by tools like Babel into plain JavaScript function calls such as React.createElement().
- For example, writing
Hello
in JSX is converted into React.createElement("h1", null, "Hello"), which produces a React element that the Virtual DOM can use to update the UI efficiently. We use JSX because it makes the code more readable, declarative, and closer to HTML, which is familiar to most web developers. Without JSX, we would have to manually call React.createElement() for every element, which becomes harder to maintain in large applications. Thus, JSX acts as a developer-friendly layer that simplifies UI building while still compiling down to efficient JavaScript.
3)Explain props vs state with an example.In React, props and state are both used to manage data, but they serve different purposes.
Props (short for properties) are used to pass data from a parent component to a child component. They are read-only, which means a child component cannot modify the props it receives—it can only display or use them.
State, on the other hand, is data that is managed within a component itself. Unlike props, state is mutable and can change over time, usually in response to user actions.
Example:
function Counter(props) {
const [count, setCount] = useState(props.initialValue);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
Here, initialValue is passed as a prop from the parent, while count is managed as state inside the component.
4)You have a counter that should increase by 2 each time a button is clicked. Why does the following not work? How would you fix it?
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count => count + 1);
setCount(count => + 1);
};
Top comments (0)