React JS Tutorial: Props vs State 🚀

beginner
8 min

React JS Tutorial: Props vs State 🚀

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 📝

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.

Creating a Component with Props 📝

jsx
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.

Using Props 💡

Parent components pass props to child components using the props attribute:

jsx
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".

Passing Multiple Props 📝

jsx
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 📝

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.

Creating a Component with State 📝

jsx
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.

Updating State 💡

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.

Props vs State 💡

  • Props are used to pass data from parent to child components. They are immutable.
  • State is used to manage local data within a component, creating dynamic content.

Quiz 🎯

Quick Quiz
Question 1 of 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! 🎉