ReasonJun

React : state / props 본문

Frontend/React

React : state / props

ReasonJun 2023. 6. 11. 01:28
728x90

In React, both state and props are used to manage and pass data in components, but they serve different purposes.

 

State:

  • State is an internal data storage specific to a component.
  • It represents the mutable data that can be changed over time.
  • State is managed and controlled by the component itself.
  • When state changes, the component re-renders to reflect the updated state.
  • State is typically initialized in the component's constructor or using React hooks.
  • To update state, you use the setState method or the useState hook (in functional components).
import React, { Component } from 'react';

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

  incrementCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

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

In the above example, the Counter component has an internal state count, which is initially set to 0. Clicking the "Increment" button updates the state, and the component re-renders with the updated count value.

 

Props:

  • Props (short for properties) are external inputs passed to a component.
  • Props are read-only and cannot be modified by the component receiving them.
  • Props are passed down from a parent component to a child component.
  • Components can use props to customize their behavior or display based on the provided data.
  • Props are accessed within a component using this.props (in class components) or as function arguments (in functional components).
import React from 'react';

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

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

In the above example, the Greeting component receives the name prop from its parent component (App). It displays a personalized greeting using the prop value.

 

Props are useful for passing data and configuration to components, allowing for reusable and flexible component composition.

 

It's important to note that while state is local to a component and managed internally, props flow from parent to child components to enable data sharing and component composition.

 

728x90

'Frontend > React' 카테고리의 다른 글

React : lifecycle  (0) 2023.06.11
React : React.Component / Component (class)  (0) 2023.06.11
React : Basic Rules for JSX  (0) 2023.06.11
React : JSX (JavaScript XML)  (0) 2023.06.11
React : Why use React? (Comparing javascript and react code)  (0) 2023.06.11
Comments