1)What is the difference between a functional component and a class component in React?
- A functional component in React is a simple JavaScript function that returns JSX and uses Hooks like useState or useEffect for state and lifecycle management. It’s easy to read and faster to write.
- A class component is the older way of building components using the ‘class’ keyword. It uses a render method and the ‘this’ keyword to show data.
- Functional components are now preferred because they make the code cleaner, simpler, and more efficient.
2)How does JSX work internally? Why do we need it instead of plain JavaScript?
- JSX stands for JavaScript XML. It allows us to write HTML-like code inside JavaScript, which makes the code easier to read and write. Internally, JSX doesn’t run directly in the browser — it’s converted by tools like Babel into normal JavaScript code using React’s createElement() function.
- We use JSX instead of plain JavaScript because it makes code easier to read, write, and maintain. Without JSX, we’d have to write long and complex JavaScript code for every element, which is harder to manage. So, JSX helps developers build user interfaces faster and more clearly.
3)What is Virtual DOM and how does React use it for rendering?
The Virtual DOM is a lightweight copy of the real DOM. When something changes in a component, React updates the Virtual DOM first, compares it with the previous version, and then updates only the parts that actually changed in the real DOM. This makes rendering faster and more efficient.
4)Explain props vs state with an example.
- Props are used to pass data from a parent component to a child component and are read-only, meaning the child can’t change them.
- State is data that is managed inside a component and can change over time, causing the component to re-render.
5)If you need to store a previous state value before update, how would you handle that?
To store a previous state value before it updates, I use the useRef() hook. It keeps a mutable value that doesn’t re-render the component. I update the ref inside a useEffect after each render, and then I can access the previous state value from ref.current.
6)What is the difference between useRef and useState? When would you choose one over the other?
useState is used when we want to store data that affects the UI — updating it triggers a re-render. useRef, on the other hand, stores a mutable value that persists across renders but does not cause re-rendering. I’d use useState for things like counters or input values, and useRef for storing previous state, DOM elements, or values I don’t want to trigger a re-render.
7)How can you use useRef to focus an input field when a button is clicked?
We can use useRef to get direct access to a DOM element. By attaching the ref to an input and calling inputRef.current.focus() inside a button click handler, we can focus the input field programmatically without re-rendering the component.
Top comments (0)