Props are pieces of data passed into a child component from the parent while state is data controlled within a component
What is State?
The state is an
updatable structure that is used to contain data or information about the
component. The state in a component can change over time. The change in state
over time can happen as a response to user action or system event. A component
with the state is known as stateful components. It is the heart of the react
component which determines the behavior of the component and how it will
render. They are also responsible for making a component dynamic and
interactive.
Here
is an example showing how to use state:
Update
a component’s state
State
should not be modified directly, but it can be modified with a special method
called setState( )
.
});
What happens when state changes? OK,
why must we use setState( )
?
A change in the state happens based on user-input, triggering an event, and so on. Also, React components (with state) are rendered based on the data in the state. State holds the initial information. So when state changes, React gets informed and immediately re-renders the DOM – not the whole DOM, but only the component with the updated state. This is one of the reasons why React is fast.
And
how does React get notified? You guessed it: with setState(
)
.
The setState( )
method
triggers the re-rendering process for the updated parts. React gets informed,
knows which part(s) to change, and does it quickly without re-rendering the
whole DOM.
In
summary, there are 2 important points we need to pay attention to when using
state:
- State
shouldn’t be modified directly – the
setState( )
should be used - State affects the performance of your app, and therefore it shouldn’t be used unnecessarily
Important: Can I use state in every component?
Another
important question you might ask about state is where exactly we can use it. In
the early days, state could only be used in class components, not in
functional components.
That’s
why functional components were also known as stateless components. However,
after the introduction of React
Hooks, state can now be used both in class and functional
components.
If your project is not using React Hooks, then you can only use state in class components.
Example
Test.js
Differences between props and state
Finally, let’s recap and see the main differences between props and state:
- Components receive data from outside with props, whereas they can create and manage their own data with state
- Props are used to pass data, whereas state is for managing data
- Data from props is read-only, and cannot be modified by a component that is receiving it from outside
- State data can be modified by its own component, but is private (cannot be accessed from outside)
- Props can only be passed from parent component to child (unidirectional flow)
- Modifying state should happen with the
setState ( )
method