In React, we do not manipulate the DOM directly when we want to update a component's view. This is because React is declarative—meaning we define how the UI should look at any given state, and React takes care of updating the DOM as needed.
But If We Don’t Manipulate the DOM, How Do We Update the Component View?
This leads us to a fundamental principle in React: React updates a component’s view by re-rendering the entire component whenever the underlying data (state) changes.
Here’s how it works visually:
Why Is React Called "React"?
React is named "React" because it reacts to state changes by re-rendering the UI automatically. When a component's state is updated, React efficiently updates the view by re-rendering only the parts of the DOM that have changed.
Updating State Based on Current State
If you're updating state based on its current value, it's important to use a callback function to avoid potential issues. Here's an example:
if (step < 3) setStep((prevStep) => prevStep + 1);
In this example, we use a callback inside setStep
to ensure that we always get the most up-to-date version of step
when performing the update. This is particularly useful in asynchronous updates.
When you're not updating state based on the current state, you don’t need to use a callback, like this:
setStep(2);
One Component, One State
Each component in React has and manages its own state. This means that no matter how many times you render the same component, each instance will maintain its own unique state. This isolation allows for scalable, reusable components across your application.
UI as a Function of State
With state, we can view the UI as a reflection of the data changing over time. The relationship between state and UI is simple: as the state changes, so does the UI.
To achieve this, we describe the UI using a combination of:
State: Holds the dynamic data.
Event Handlers: Respond to user interactions like clicks.
JSX: The declarative syntax that React uses to define the UI.