Mark As Completed Discussion

Working with State and Props

In React, state and props are used to manage and pass data between components.

State

State is a built-in concept in React that represents the mutable data that is specific to a component. It allows components to manage and update their own data. Whenever the state of a component changes, React automatically re-renders the component to reflect the updated state.

In the example below, we have a ShoppingCart component that uses state to keep track of the number of items in the shopping cart:

SNIPPET
1import React, { useState } from 'react';
2
3function ShoppingCart() {
4  const [itemCount, setItemCount] = useState(0);
5
6  function addToCart() {
7    setItemCount(itemCount + 1);
8  }
9
10  return (
11    <div>
12      <h1>Shopping Cart</h1>
13      <p>Total items: {itemCount}</p>
14      <button onClick={addToCart}>Add to Cart</button>
15    </div>
16  );
17}
18
19export default ShoppingCart;

In the example above, we define a ShoppingCart component that uses the useState hook to create a state variable itemCount and a setter function setItemCount. The initial value of itemCount is set to 0.

When the addToCart function is called, it increments the itemCount value by 1 using the setItemCount function. This triggers a re-render of the component, and the updated value of itemCount is displayed in the UI.

Props

Props (short for properties) are used to pass data from a parent component to a child component. They are read-only and cannot be modified by the child component.

Here is an example of a parent component App passing a prop name to a child component Greeting:

SNIPPET
1import React from 'react';
2
3function App() {
4  const name = 'John';
5
6  return (
7    <div>
8      <h1>Welcome, {name}!</h1>
9      <Greeting name={name} />
10    </div>
11  );
12}
13
14function Greeting({ name }) {
15  return <p>Hello, {name}!</p>;
16}
17
18export default App;

In the example above, the App component passes the name prop to the Greeting component using the syntax {name={name}}. The Greeting component receives the name prop as a parameter and uses it to display a personalized greeting.

By using state and props, you can manage and pass data between components in React, enabling you to build dynamic and interactive user interfaces.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment