DEV Community

Kavya S
Kavya S

Posted on

React Question & Answer

1. What is the difference between a functional component and a class component in React?

  • Functional component is a javascript function that takes props and returns a react element(jsx) while class component use render() method, which returns the JSX
  • Implements hooks easily within the function to handle state and effects but in class component,states are handled through class methods
  • Hooks handle state initialization but in class component requires a constructor for initializing state

2. How does JSX work internally? Why do we need it instead of plain JavaScript?

JSX is like a shortcut that gets converted to regular JavaScript. When you write JSX like <h1>Hello</h1>, it gets turned into React.createElement('h1', {}, 'Hello') behind the scenes.

why we need?
JSX makes writing React code much easier and cleaner. Without JSX, you'd have to write long, complicated JavaScript code to create simple HTML elements. JSX looks like HTML so it's familiar and easy to read.

3. What is Virtual DOM and how does React use it for rendering?

Virtual DOM acts as a bridge between UI and real DOM.
It updates only the specific part of the page we need to change.
If we update any components in a web page,it first update the changes in virtual DOM and it compare it with Real DOM.
If it updates in actual DOM,it takes more time to update but virtual DOM makes it faster.

4. Explain props vs state with an example.

  • Props are properties that is passed from a parent component to a child component
  • but in state,it can change over time based on user interactions or API responses.
  • Props can be used with state and functional components and The state can be used only with the state components/class component
  • Props are read-only,State can be updated with setState

Example for props

// Parent Component
function App() {
  return <User name="John" age={25} />;
}

// Child Component
function User(props) {
  return (
    <div>
      <h1>Name: {props.name}</h1>
      <p>Age: {props.age}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Example for State

function Counter() {
  const [count, setCount] = useState(0); // STATE

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

5) What is lifting state up in React? Give an example.

Lifting State Up is a pattern in React where you move the state from a child component to its parent component, allowing multiple child components to share and synchronize the same state data. [to be discussed]

Top comments (0)