Can you explain the concept of state and props in React.js and how they differ from each other?
State is data that a component can change and use to re-render itself. Props are data passed from a parent component to a child component that the child can’t change. State is managed inside the component, while props come from outside. State is for internal data, and props are for external data.
Understanding State Updates and useEffect Behavior
Answer
How can you modify the code to ensure the setTimeout callback always logs the updated state value?
Answer
Predict output 3
Answer
Predict output 4
Answer
Effects run after rendering
Synchronous operations:
The useEffect callback runs
First console.log executes (synchronously)
Promise.resolve is created and its .then callback is queued to the microtask queue
unmount() (setShow(false)) is called synchronously
React processes this state update immediately in the same synchronous execution
Component unmounts, running cleanup effects
Microtask queue:
After the synchronous code finishes, the microtask (.then callback) executes
By this time, the component is already unmounted
The key insight is that even though useEffect itself is asynchronous, once React starts running effects, it follows a specific order:
Parent effects before child effects (if effects in custom hooks)
All effect cleanups run before all new effects
Effects run in the order they were defined