Understanding React Components: Props and State
Mark Ezema / February 15, 2019
2 min read •
React Components: Props and State
React components are functions which return JSX, and there are two important concepts to understand when working with React: props and state.
Props
Props are the input arguments of a React function component, and are immutable, meaning they cannot be changed. To think of props, imagine a function that is called with a set of arguments. These arguments can be anything: numbers, strings, arrays, objects, functions, etc.
State
State is data that changes over the lifetime of a React component instance. To track dynamic values that change over time, we use React.useState()
to set the state internally in the component.
Let’s look at an example. Imagine a simple addition component that has two inputs, n1
and n2
. If the user changes the value of n2
, we want to track this change using state. To do this, we would set the state internally in the component using React.useState()
.
For example, we might want to start with a value of 3 for n2
instead of 0. This is where props come in. We can pass in the initial value as a prop, just like we passed in n1
to our example. Here is how the component would look:
function AddWithInput({n1, initialN2 = 0}) {
const [n2, setN2] = React.useState(initialN2)
function handleInputChange(event) {
const input = event.target
const newN2 = Number(input.value)
setN2(newN2)
}
return (
<div>
{n1} +{' '}
<input type="number" value={n2} onChange={handleInputChange} /> ={' '}
{n1 + n2}
</div>
)
}
And when we use the component, we can pass in the initial value of n2
like so:
<AddWithInput n1={2} initialN2={3} />
This will start with a n2
value of 3 instead of 0.
Summary
To sum it up, props are for passing in data into a component, while state is for tracking values that change over the lifetime of a component. Props are not meant to be changed, but state is meant to be updated and re-rendered as needed.
Props and state are important concepts to understand when working with React components. With the right understanding of these two concepts, you can write effective React components and build powerful applications.
Subscribe to the newsletter
Get emails from me about updates in the world of Artificial Intelligence, and Personal Development.