State and Props in React

In React, state and props are two important concepts that help to manage and pass data between components. State is a JavaScript object that represents the current state of a component. It stores data that determines the behavior and rendering of the component. When the state of a component changes, React will automatically re-render the component to reflect the updated state.

State can be created and managed in functional components using the useState hook, or in class components using the setState method.

Props, short for properties, are a way to pass data from a parent component to a child component. Props are read-only, meaning they cannot be modified by the child component. Instead, the child component uses props to determine how to render itself.

Props are passed to a component as attributes in JSX, and they can be accessed in the component as a JavaScript object.

By using state and props, React allows us to create modular and reusable components that can be easily composed to build complex user interfaces.

import React, { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

In this example, we use state to store the count value of the counter component. Whenever the button is clicked, the handleClick function is called and it updates the count state by incrementing the value by 1. This causes the component to re-render, displaying the updated count value.


2. User Component using Props:

import React from 'react';

function User(props) {
  return (
    <div>
      <h1>{props.name}</h1>
      <p>{props.email}</p>
    </div>
  );
}

In this example, we use props to pass user data to the User component. The name and email data are passed to the component as props, and they are rendered inside the component. This allows us to reuse the User component with different user data.


3. Input Component using State:

import React, { useState } from 'react';

function Input() {
  const [text, setText] = useState('');

  function handleChange(event) {
    setText(event.target.value);
  }

  return (
    <div>
      <input type="text" value={text} onChange={handleChange} />
      <p>You typed: {text}</p>
    </div>
  );
}

In this example, we use state to store the value of the input field. Whenever the user types in the input field, the handleChange function is called and it updates the text state with the new value. This causes the component to re-render, displaying the updated value in the paragraph below the input field.


4. ProductList Component using Props:

import React from 'react';

function ProductList(props) {
  return (
    <ul>
      {props.products.map(product => (
        <li key={product.id}>
          {product.name} - ${product.price}
        </li>
      ))}
    </ul>
  );
}
In this example, we use props to pass an array of products to the ProductList component. The map function is used to loop through the array of products and render each product as an li element. This allows us to reuse the ProductList component with different arrays of products.

5. TodoList Component using State and Props:

import React, { useState } from 'react';
import Todo from './Todo';

function TodoList() {
  const [todos, setTodos] = useState([]);

  function handleAddTodo() {
    const newTodo = prompt('Enter a new todo:');
    setTodos([...todos, { text: newTodo, completed: false }]);
  }

  return (
    <div>
      <button onClick={handleAddTodo}>Add todo</button>
      <ul>
        {todos.map((todo, index) => (
          <Todo key={index} text={todo.text} completed={todo.completed} />
        ))}
      </ul>
    </div>
  );
}
In this example, we use state to store an array of todos, and we use props to pass todo data to the Todo component. The handleAddTodo function is called when the user clicks the "Add todo" button, and it prompts the user to enter a new todo item.

Most Helpful This Week