27
loading...
This website collects cookies to deliver better user experience
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.Form
component with the item as the parameter, like <Form item="Milk">
....
<Form item = "Milk" />
...
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>
)
}
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
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>
)
}
state
.props
.state
variable that is set to that prop
and update the state
variable as you wish.