State and props are two fundamental concepts in React.js that allow you to manage and pass data within your components. They play crucial roles in creating dynamic and interactive user interfaces. Let's explore the concepts of state and props in React:
State:
1. Component State:
State is a JavaScript object that represents the dynamic data of a component.
It is used to store and manage data that can change over time within a component.
State is initialized in the constructor of a class component and can be updated using the setState method.
You should not directly modify the state; instead, use setState to update it.
React may batch multiple setState calls for performance reasons, so you should use the functional form of setState when the new state depends on the previous state.
Example:
// Incorrect
this.state.count = this.state.count + 1; // Do not do this
// Correct
this.setState((prevState) => ({ count: prevState.count + 1 }));
Props:
1. Component Props:
Props (short for properties) are a way to pass data from a parent component to a child component.
Props are read-only and help make your components reusable and configurable.
Props are passed as attributes to a component in JSX.
Example:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
const element = <Welcome name="Alice" />;
2. Default Props:
You can define default values for props using defaultProps in a functional or class component.
Example (Functional Component):
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
In summary, state allows you to manage dynamic data within a component, while props enable data flow from parent to child components. Understanding when to use state and when to use props is essential for building React applications that are both interactive and modular.