Welcome to the Props vs State lesson! Today, we'll delve into understanding two fundamental concepts in React JS: Props and State. Let's get started! 🎯
Props (short for properties) are used to pass data from parents to child components. They are immutable, meaning they cannot be changed within the child component.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}In the example above, we've created a Greeting component that accepts a props object, which contains a name key.
Parent components pass props to child components using the props attribute:
function App() {
return (
<div>
<Greeting name="John" />
</div>
);
}In the example above, we've created an App component that includes a Greeting component, and we've passed it a name prop with the value "John".
function Greeting(props) {
return <h1>Hello, {props.name}! You are {props.age} years old.</h1>;
}Now, the Greeting component accepts two props: name and age.
State is used to manage the local data within a component. You can think of state as a way to create dynamic content within your components.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}In the example above, we've created a Counter component using the useState hook, which allows us to manage the local state within the component.
We update the state using the setCount function provided by the useState hook. In the example above, when the button is clicked, the count is incremented by 1.
What is the main difference between Props and State in React?
That's it for today! In the next lesson, we'll explore more advanced concepts in React JS. Keep learning and practicing! 🚀
Stay tuned for more lessons! 🎉