What is the difference between state and props in React?
TL;DR
In React, state
is a local data storage that is managed within a component and can change over time, while props
are read-only attributes passed from a parent component to a child component. State is used for data that changes within a component, whereas props are used to pass data and event handlers to child components.
What is the difference between state and props in React?
State
State is a built-in object in React components that holds data or information about the component. It is managed within the component and can change over time, usually in response to user actions or network responses. When the state changes, the component re-renders to reflect the new state.
- State is local to the component and cannot be accessed or modified outside of it
- State can be initialized in the constructor of a class component or using the
useState
hook in a functional component - State changes are asynchronous and should be done using the
setState
method in class components or the updater function returned byuseState
in functional components
Example of state in a class component:
Example of state in a functional component:
Props
Props (short for properties) are read-only attributes passed from a parent component to a child component. They are used to pass data and event handlers down the component tree. Props are immutable, meaning they cannot be changed by the child component.
- Props are passed to the child component as an argument to the component function or as a property on the
this
object in class components - Props allow components to be reusable by passing different data to them
- Props can be used to pass functions as well, enabling child components to communicate with parent components
Example of props in a class component:
Example of props in a functional component:
Key differences
- State is managed within the component, while props are passed from a parent component
- State can change over time, while props are immutable
- State is used for data that changes within a component, while props are used to pass data and event handlers to child components