Skip to content

Instantly share code, notes, and snippets.

@thecatfix
Last active September 5, 2024 10:33
Show Gist options
  • Save thecatfix/2fa8eb5a55cd67f71ce16931a3c54d17 to your computer and use it in GitHub Desktop.
Save thecatfix/2fa8eb5a55cd67f71ce16931a3c54d17 to your computer and use it in GitHub Desktop.
Gist from Drafts

Understanding State and Props in React

In React, state and props are two fundamental concepts that are essential for managing data and building interactive components. Understanding the difference between state and props and how to use them effectively is crucial for React.

📘 What is State in React?

State is a built-in React object that is used to hold data or information about the component. A component’s state can change over time; whenever it changes, the component re-renders itself. State is managed within the component (similar to variables declared within a function) and can be changed with the setState function in class components or the useState hook in functional components.

Characteristics of State

  1. Mutable: State is mutable, meaning it can be changed. When state changes, React re-renders the component to reflect the updated state.
  2. Local to the Component: State is local or encapsulated within the component and cannot be accessed or modified outside of it unless it is passed down to child components.
  3. Triggers Re-Rendering: Any change in the state triggers a re-render of the component, allowing the user interface to update dynamically based on user interactions or other changes.

How to Use State

In class components, state is usually initialized in the constructor:

import React, { Component } from 'react';

class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };  // Initialize state
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });  // Update state
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

export default Counter;

In functional components, the useState hook is used to manage state:

import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);  // Initialize state using useState hook

  const increment = () => {
    setCount(count + 1);  // Update state
  };

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

export default Counter;

Common Use Cases for State

• Managing form inputs and their values. • Handling user interactions like button clicks or mouse movements. • Fetching and displaying data from an API and updating the UI based on the fetched data.

🛠️ What are Props in React?

Props (short for “properties”) are used to pass data from parent components to child components. Props are read-only and cannot be modified by the child component receiving them. They are similar to function parameters, and components use props to communicate with each other.

Characteristics of Props

  1. Immutable: Props are immutable, meaning they cannot be changed by the component that receives them. They are meant to be passed down from parent to child components to convey information.
  2. Passed from Parent to Child: Props are passed from a parent component to a child component, enabling dynamic rendering of content.
  3. Used to Customize Components: Props allow for customization and configuration of child components based on data passed from the parent component.

How to Use Props

Props are passed to components similarly to how arguments are passed to functions._

Class components use this.props to access props:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

export default Greeting;

Functional components access props directly as function arguments:

import React from 'react';

const Greeting = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

export default Greeting;

Passing Props to a Component

import React from 'react';
import Greeting from './Greeting';

const App = () => {
  return (
    <div>
      <Greeting name="John" />
      <Greeting name="Jane" />
    </div>
  );
};

export default App;

In the example above, the Greeting component receives a name prop, which it uses to display a personalized greeting. The App component passes different values for the name prop, demonstrating how props can be used to customize components.

🔄 Key Differences Between State and Props

Feature State Props
Definition A local data storage that is local to the component and can be modified. A way to pass data from parent to child components.
Mutability Mutable – can be changed using this.setState in class components or useState in hooks. Immutable – once set, cannot be changed by the child component.
Scope Local to the component. Passed from parent to child, cannot be accessed or modified by the child.
Usage Used for storing data that can change over time (user input, API responses, etc.). Used to pass data and event handlers down to child components.
Re-Renders Component Yes, changing state triggers a re-render of the component. No, changing props in the parent component re-renders the child component if the props change.
Access this.state in class components, useState in functional components. this.props in class components, props in functional components.

🏗️ Practical Examples of Using State and Props

Example: Counter with State and Props

Consider a counter application where the parent component maintains - The counter value,

Child component displays it Provides buttons to increase or decrease the counter.

Parent Component (App):

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

const App = () => {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);
  const decrement = () => setCount(count - 1);

  return (
    <div>
      <h1>Counter App</h1>
      <Counter count={count} onIncrement={increment} onDecrement={decrement} />
    </div>
  );
};

export default App;

Child Component (Counter):

import React from 'react';

const Counter = ({ count, onIncrement, onDecrement }) => {
  return (
    <div>
      <p>Current Count: {count}</p>
      <button onClick={onIncrement}>Increment</button>
      <button onClick={onDecrement}>Decrement</button>
    </div>
  );
};

export default Counter;

In this example:

• State: The App component uses the useState hook to manage the counter state (count). • Props: The App component passes the count state and increment/decrement functions as props to the Counter component.

📌 Remember

State and props are integral parts of React that enable components to manage and share data effectively. Understanding when to use state and when to use props is crucial for building scalable and maintainable React applications.

While state is used for managing data that changes over time within a component, props are used to pass data from parent to child components, allowing for dynamic and interactive user interfaces.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment