Consider this React code snippet:
const root = document.getElementById('root');
ReactDOM.render(<h1>First</h1>, root);
ReactDOM.render(<h1>Second</h1>, root);What will be displayed inside the root element after both calls?
const root = document.getElementById('root'); ReactDOM.render(<h1>First</h1>, root); ReactDOM.render(<h1>Second</h1>, root);
Think about how ReactDOM.render replaces content in the container.
ReactDOM.render replaces the content inside the container each time it is called. The second call overwrites the first, so only 'Second' is shown.
When ReactDOM.render is called on a container that already has a React component rendered, what lifecycle behavior happens to the existing component?
React tries to reuse components when possible.
ReactDOM.render updates the existing component by passing new props and re-rendering it instead of unmounting and remounting.
What happens if you call ReactDOM.render(<App />, null) or with an undefined container?
ReactDOM.render(<App />, null);ReactDOM.render expects a real DOM element as container.
Passing null or undefined as container causes ReactDOM.render to fail because it tries to access properties of the container element.
Given this React component:
function Counter() {
const [count, setCount] = React.useState(0);
return <div>Count: {count}</div>;
}If ReactDOM.render(<Counter />, root) is called, then later ReactDOM.render(<Counter />, root) is called again, what will be the displayed count?
function Counter() { const [count, setCount] = React.useState(0); return <div>Count: {count}</div>; } ReactDOM.render(<Counter />, root); // Later ReactDOM.render(<Counter />, root);
Think about whether state persists between separate ReactDOM.render calls.
Each ReactDOM.render call creates a new component instance, so state resets to initial value 0.
Consider this class component:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.state.count += 1;
}
render() {
return <div>Count: {this.state.count}</div>;
}
}After calling increment() and then ReactDOM.render(<MyComponent />, root) again, the UI does not update. Why?
class MyComponent extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment() { this.state.count += 1; } render() { return <div>Count: {this.state.count}</div>; } } // Usage const root = document.getElementById('root'); const comp = new MyComponent(); comp.increment(); ReactDOM.render(<MyComponent />, root);
How does React detect state changes in class components?
Directly mutating this.state does not trigger React's update mechanism. setState must be used to notify React of changes.