Conteúdo do curso
Advanced React: Props and State
Sobre a Aula

Integration of Props and State for Effective Communication Between Different Components

In React, Props and State are essential for communication between components. Props allow passing data from a parent component to a child component.

State manages internal data of a component. Let’s see how these two concepts work together.

Props: Passing Data from Parent to Child

Props are arguments passed to React components. They are immutable, meaning they cannot be changed by the receiving component. Here’s a simple example:

// Parent Component
function Parent() {
  const message = "Hello from Parent!";

  return <Child text={message} />;
}

// Child Component
function Child(props) {
  return <div>{props.text}</div>;
}

In this example, Parent passes the prop message to the Child component. The Child component receives this prop and displays it.

State: Managing Internal Data

State is used to store data that can change. It is managed within the component where it was declared. Here’s a basic example:

import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

Here, Counter uses useState to create a state count and a function setCount to update it. The value is displayed and can be incremented by clicking the button.

Integration of Props and State

Now, let’s see how to integrate Props and State for effective communication between components.

  1. Updating State from Props: A child component can inform changes to the parent component, which updates its state and passes it as a prop to the child. See:
// Parent Component
import { useState } from 'react';

function Parent() {
  const [message, setMessage] = useState("Initial Message");

  const updateMessage = (newMessage) => {
    setMessage(newMessage);
  };

  return <Child text={message} updateText={updateMessage} />;
}

// Child Component
function Child(props) {
  const newMessage = "Child's Updated Message";

  return (
    <div>
      <p>{props.text}</p>
      <button onClick={() => props.updateText(newMessage)}>
        Update Message
      </button>
    </div>
  );
}

In this example, Parent passes a text prop and an updateText function to Child. The child displays text and uses updateText to inform the parent when the message should be updated.

The parent then updates its state and passes the new message to the child.

Conclusion

The integration of Props and State allows React components to communicate efficiently. Props are used to pass data and functions between components.

State manages the internal data that can be dynamically updated. This combination is powerful for creating dynamic and interactive interfaces.

Entrar na conversa
Rolar para cima