In React, to create a UI with two buttons (Increment and Decrement), we use the onClick event instead of addEventListener in JavaScript. The function can be defined separately or directly inside {} in JSX.
Why Doesn't UI Update Initially?
When clicking the buttons, console.log(count) shows the value changing, but the UI does not update. In vanilla JavaScript, we manually manipulate the DOM to reflect the changes. While we can do the same in React by selecting tags and updating them, React handles DOM manipulation internally, keeping our code clean.
Why Clean Code Matters?
Direct DOM manipulation results in repeated code, especially when updating the same variable across multiple elements.
React simplifies this by introducing hooks, which are just functions.
The most commonly used hook is useState.
Understanding useState
When a variable's value changes, we say its state is changing. The useState hook helps manage state in React.
const [count, setCount] = useState(0);
useState(0) returns an array with two values:
count → initialized with 0.
setCount → a function to update count.
Why a function? Instead of direct manipulation, React says:
"Call my function (setCount(newValue)) whenever you update the variable, and I’ll handle UI updates automatically."
How does React update the UI?
When setCount(count) is called, React rerenders the component.
Any JSX that uses count will automatically show the updated value.
This prevents repetitive code for updating the UI.
Understanding Sorting in JavaScript
let arr = [10, 2, 5, 1];
arr.sort((a, b) => a - b);
console.log(arr); // Output: [1, 2, 5, 10]
If a - b is negative, a comes first.
If positive, b comes first.
The useState Twist 🚀
React prevents unnecessary re-renders to optimize performance. Example:
const arr = [8, 5, 9, 7, 4];
const [temp, setArr] = useState(arr);
temp stores the array and is displayed in the UI.
Suppose we sort it and update state:
temp.sort((a, b) => a - b);
setArr(temp);
Issue: UI doesn’t update.
Why?
JavaScript stores primitive values in the stack, but arrays & objects are stored in the heap.
The stack only holds a reference (address) to the heap’s array.
After sorting, the same reference remains, so React sees no change and doesn’t rerender.
Solution? Clone the array!
setArr([...temp]); // Creates a new array with a different address.
Now, React detects the state change and updates the UI.
filter() in JavaScript
Returns a new array based on a condition.
React’s power lies in efficient rendering, avoiding unnecessary DOM updates and keeping performance optimized.