Pass usestate setter to child

“`HTML

Parent Component

Count: 0

Parent Component

Text: Hello World


“`

In the given examples, we have a parent component and a child component where the state of the parent component is passed to the child component as a prop. The child component can then modify the state of the parent component through the provided setter function. Here’s a breakdown of how it works:

In Example 1:
1. The parent component has a count state variable initialized to 0. It also has an `updateCount` function that increments the count by 1 and updates the display.
2. The child component receives the `setCount` prop which is the setter function for updating the count state in the parent component.
3. When the child component’s button is clicked, the `handleClick` function is invoked. Inside the function, `setCount(count + 1)` is called to update the count state in the parent component.
4. This results in re-rendering the parent component with the updated count.

In Example 2:
1. The parent component has a text state variable initialized to “Hello World”. It also has an `updateText` function that updates the text to “Hello CSS” and updates the display.
2. The child component receives the `setText` prop which is the setter function for updating the text state in the parent component.
3. When the child component’s button is clicked, the `handleClick` function is invoked. Inside the function, `setText(“Hello JavaScript”)` is called to update the text state in the parent component.
4. This results in re-rendering the parent component with the updated text.

Note: The code provided is a combination of HTML and JavaScript, where JavaScript is used to manage the state and functionality, and HTML is used to display the components and handle user interactions.

Leave a comment