What's the difference between props and state in React?
Here is a definition of each:
"props" (short for "properties") is a special keyword in React, and is used for passing down data from one component to another.
"state" is data that changes over the lifetime of a specific instance of a React component.
Let's dive into each.
Props are used to customize Components when it’s being created and give it different arguments.
import React from 'react'
function Topic(props) {
return(
<div>
{props.name}
</div>
)
}
One of the most important features of props is that they can be passed by a parent component to its child components. This allows us to create a component that can be customized with a new set of props every time we use it. This is similar to passing arguments to a function.
import React from 'react'
function Welcome() {
return(
<div>
<p> Welcome to React, today you will learn: </p>
<Topic name="Props"/>
<Topic name="State"/>
</div>
)
}
Props are passed to the component and are fixed throughout its lifecycle. But there are cases when we want to use data that we know is going to change overtime and store that data. In this case we use something called state.
To use state we must import a React Hook called useState
import React, { useState } from "react"
Figuring out where you need state is an important task as well because we only want to set state if we really need to, and which other child components are going to be using this state.
Some examples of when to use state is when something on your app updates or changes :
- Counter
- Toggle On/Off
- Like button feature
- User inputs (forms)
- etc..
State allows React components to dynamically change output over time in response to certain events. Events such as onClick, onSubmit, and onChange are a few key examples of the events that can alter the state.
import React, { useState } from "react"
function addLikes() {
const [likes, setLikes] = useState(0)
}
Here we set the initial state of the likes to be set at 0, and depending on where we implement this state will alter the count of likes which then updates state.
The difference between props and state is that props are passed down from other components to there child components and props are updated in the child component, and props that are just going to display some text like a header or a description there value wont be changed because they are just going to display some text.
State lives inside a component and is handled inside of that component while props are handled outside of the component.
You can pass down your state as a prop and use it in a child component for something like a like button that will increase likes. After the like button is clicked react sends that information back up to the component which is handling the state and it gets updated there.
Resources:
https://www.youtube.com/watch?v=IYvD9oBCuJI - Web Dev Simplified
https://reactjs.org/docs/components-and-props.html - React Docs
Top comments (0)