- Published on
React's Props and State
- Authors
- Name
- Kieran Hauser
The Difference Between React's Props and State
React is a popular JavaScript library used for building user interfaces. When building components in React, you'll often hear developers talk about two important concepts: props and state.
Props and state are both ways to pass data to a component, but they serve different purposes. In this article, we'll explain the difference between props and state in a way that a 5-year-old could understand, with some code examples to illustrate the concepts.
Props
Props is short for "properties", and they are like the ingredients you use to make a cake. Just like how you need flour, sugar, and eggs to make a cake, a component in React needs props to work properly.
Props are passed to a component from its parent component, like how your mom might give you some eggs to use in your cake. Once the component receives its props, it can use them to render its content.
Here's an example of a simple component that receives a prop:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
ReactDOM.render(<Greeting name="Alice" />, document.getElementById('root'));
In this example, we define a Greeting
component that receives a prop called name
. We use this prop to render a personalized greeting. When we render the Greeting
component with name="Alice"
, it will render "Hello, Alice!" on the screen.
State
State is like a toy box that a component can play with. Just like how you can put different toys in your toy box and play with them, a component in React can have different states and update them as needed.
State is managed within a component, and it can be changed over time based on user interactions or other events. When the state changes, the component will re-render with the updated content.
Here's an example of a simple component that uses state:
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You clicked the button {count} times</p>
<button onClick={handleClick}>Click me</button>
</div>
);
}
ReactDOM.render(<Counter />, document.getElementById('root'));
In this example, we define a Counter
component that uses state to keep track of how many times a button has been clicked. We use the useState()
hook to define the initial state of count
as 0. When the button is clicked, we update the state using the setCount()
function. This causes the component to re-render with the updated count value.
Conclusion
In summary, props and state are two important concepts in React that serve different purposes. Props are like the ingredients you use to make a cake, while state is like a toy box that a component can play with. By understanding the difference between props and state, you'll be able to build more complex and powerful components in React.