Props vs. State
Analogy | Absence | Example
Posted on July 6, 2021
props
and state
are extremely useful ways to store information in React. That said, they can be easily confused. Here's a basic primer that I wrote for myself to better understand both how they are different and how they can be used together.
Props
Props are to components as parameters are to functions. Let's say you have a simple program to create a shopping list. You have a List component that shows all the items and a Form component where you can enter an item from scratch or edit an item that already exists. In the circumstance where you want to edit an item that already exists, you want to present the user with the Form component already populated with the item so that they can edit it from, say, "Milk" to "Soy Milk". In that case, you would call the Form
component with the item as the parameter, like <Form item="Milk">
.
...
<Form item = "Milk" />
...
The Form
component would reference that parameter as a prop
like so:
const Form = (props) => {
return(
<div>
<input
type="text"
value={props.item}
onChange={(e) => handleInputChange(e.currentTarget.value)} />
</div>
)
}
The important thing to remember about props
is that props
are read-only inside the component they are passed into. They must originate from outside the component, and they can only be updated outside the component.
State
State, by contrast, is initialized inside the component and can be updated inside the component.
A common and useful way to use state
with props
is to create a state variable from the passed-in prop. Then you can update the state variable however you want. Using the example above, you would do the following:
const Form = (props) => {
const [item, setItem] = useState(props.item);
return(
<div>
<input
type="text"
value={item}
onChange={(e) => handleInputChange(e.currentTarget.value)} />
</div>
)
}
What to use for what
Remember the following:
- If you have a value that will be created (and possibly updated) from inside that component, you need to use
state
. - If you have a value that will be used inside a component that was created outside the component, just use
props
. - If you have a value that may be updated inside a component that was created outside the component, create a
state
variable that is set to thatprop
and update thestate
variable as you wish.
Posted on July 6, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.