1. Components
Components in React are independent building blocks that can be reused. They are divided into smaller UI elements and can be combined to form larger components. For example, an application can have components such as Header, Sidebar and Content. Each component has its own responsibilities and can receive props and state to display corresponding data.
Example:
// Functional Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Class Component
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
2. Props
Props in React are values passed into components from the outside. They help to pass data from parent components to child components. Props are read-only and cannot be changed inside the component. To use props, we pass values to the component's attributes and use them in the UI part.
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
ReactDOM.render(<Greeting name="John" />, document.getElementById('root'));
3. State
State in React is mutable data that can be changed within a component. Each component can have its own state to store and manage dynamic data. When the state changes, React automatically updates the corresponding user interface. State is managed only in class components and is initialized in the component's constructor. To update the state, we use the `setState()` method.
Example:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.increment()}>Increment</button>
</div>
);
}
}