There are so many videos and documentation out there to help you learn the concept and usage of State and Props with code examples. this article is not about teaching you these concepts from scratch or providing you with code examples. The main point of this blog is to briefly give you a practical summary of what they are and when to use them. So, if you are completely new to these concepts, I would suggest you first watch some basic tutorials about them to get the most out of this summary.
State
What is State?
The state variable is a plain JavaScript object used by React that includes all information about the component's current situation. State variables are immutable and private to that component.
When do we need a state for a component?
- Whenever you need to change/update part of the UI
- Whenever the user is supposed to interact with the UI
- Whenever you need to persist local variables between renders
Using state correctly:
- States are immutable. The component that owns a piece of the state, should be the one that modifies it. Do not modify the state directly. Instead, use setState().
- State updates may be asynchronous. So, if you need to use the value of this.props and this.state to calculate the next state value, instead of directly passing an object to setState() pass a callback function with the state and props as arguments.
- State updates are merged.
- The data flows down.
How does setState() work?
This method tells React that we are updating the state. Then, React checks which parts of the state are changed to bring the DOM in sync with the virtual DOM based on those changes.
Note: props is basically a plain JavaScript object that includes all the attributes that we set in the parent component. Every React component has the props property. It is used to pass data from a parent component to a child. It is “read-only” and cannot be modified, if we need to do so, we should use setState and modify them from the state.
State vs props
Ownership and Control:
State: Internal data, owned and controlled by the component itself.
Props: External data, owned and controlled by the parent component.
Conceptual Understanding:
State: Can be thought of as the component's memory, holding data over time across multiple re-renders.
Props: Like function parameters, used to pass data from parent to child components.
Mutability and Effects:
State: Can be updated by the component itself, triggering a re-render.
Props: Read-only, cannot be modified by the receiving component. Receiving new props also causes a re-render.
Usage:
State: Used to make components interactive.
Props: Used to configure child components from the parent component.
Note: Whenever a piece of state is updated, the component that owns the state, and all children components that receive the piece of state as props will be re-rendered to keep in sync.
Top comments (0)