Difference between a state and prop in react | React interview question.
In this article we are going to see the difference between state and props in React. First let's see what are state and props individually.
# Props
Props are something that a component receives from where it is rendered (consider as arguments). In the example below we are rendering Header component and passing a prop title to it. It is same like calling Header component with an object
{title: 'Home'} // --------------- <> <Header title="Home" /> ... </>
State
A state can be considered as a local variable in the component that cannot be accessed outside of the component.
const [count, setCount] = useState(0);
Similarities
- Both are responsible for what a component should render i.e. the app will rerender if a prop or state changes
- A state and prop both can be passed down as props to child components
Differences
- A state is both readable and writable but on the other hand a prop is read-only.
- The initial value for a state is set inside the component and for a prop we may set the default value inside the component where the prop is sent to.
- Props are usually used for rendering reusable components with static content and a state can change over time depending on various conditions/ user interactions.
stateVsProp
State
props
javaScript
reactjs