React 1
React 1
What is useState?
● The [count, setCount] syntax means we are declaring a state variable (count) and a function
(setCount) to update it.
● When we click the button, setCount(count + 1) updates the state, and React re-renders the
component to show the new value.
● Relation to JavaScript: Just like we store values in variables using let count = 0;, here we
store it in React’s state, but React remembers its value between re-renders.
How Does useState Work?
In React, render means displaying the UI on the screen. Every time React
renders(load) a component, it converts JSX into actual HTML elements and
updates the DOM.
1⃣ What Happens During a Render?
1. JSX is converted to HTML (React translates JSX into real DOM elements).
A state in React is a built-in memory of a component that stores values that can
change over time.
🔹 State management means controlling how and where data is stored, updated
and shared in an app.
It ensures:
useEffect is a React Hook that lets you perform side effects in function
components. Side effects include:
useEffect(() => {
return () => {
};
}, [dependencies]);
● First argument: A function that runs after the component renders.
● Second argument (dependencies array): Controls when the effect runs.
useEffect is a React Hook that lets you perform side effects in a function
component.
For example:
In programming, a side effect is an extra action that happens outside of the function itself.
First, What Happens When a Component Loads?
Yes, useEffect is called automatically after the component loads, but unlike state
(useState), it does NOT run during rendering.
When we say "automatically run," it means that useEffect executes after React
renders the component. However, how many times it runs depends on the
dependency array inside useEffect.
Case 1: useEffect Without a Dependency Array (Runs on Every Render)
What Happens?
● When you click "Increase" button → useEffect runs again after every render.
● When the page loads → useEffect runs (✅ useEffect ran once! in console).
Use Case: Fetching API data only once when the page loads.
🔹 Case 3: useEffect With a Dependency ([count]) (Runs Only When count Changes)
Click "Increase" button → useEffect runs again every time count updates.
If other state changes, but count stays the same, useEffect does NOT run.
React State Interview Questions (Beginner to Advanced)
🔹 Beginner-Level Questions
1⃣2⃣ How does React optimize state updates with the Virtual DOM?
1⃣3⃣ What are uncontrolled and controlled components, and how does state play a
role in them?
1⃣4⃣ How do you handle deeply nested state updates in React?
1⃣5⃣ What is a state reducer, and how is it different from useState?
1⃣6⃣ What are common performance issues related to state updates, and how can
we optimize them?