Props and State
PROPS
Props, short for properties, are read-only
and immutable data
passed from parent to child components. They are mainly used to transfer data between components and ensure reusability.
Key Features of Props
- Read-Only: Cannot be modified by the child component.
- Used in Functional and Class Components.
- PropTypes: Ensures props are of the correct data type during development.
age: PropTypes.number; // Throws a warning if a non-number is passed.
4.DefaultProps: Provides default values for props when none are passed.
name: "Guest"; // Default value for the name prop.
Code Example
Student.jsx
import PropTypes from 'prop-types';
export default function Student(props) {
return (
<div>
<p>Name: {props.name}</p>
<p>Age: {props.age}</p>
<p>Student: {props.isStudent ? 'Yes' : 'No'}</p>
</div>
);
}
// PropTypes
Student.propTypes = {
name: PropTypes.string,
age: PropTypes.number,
isStudent: PropTypes.bool,
};
// DefaultProps
Student.defaultProps = {
name: 'Guest',
age: 0,
isStudent: false,
};
STATE
State is an object within a component that holds dynamic values which can change over time. States are mutable and are generally used for user interactions and events.
Key Features of State
- Can only be used in Class Components (in older React).
- Mutable: Updated using this.setState().
- Tracks dynamic data such as user inputs or real-time responses.
App.jsx Implementation
Props are passed from the App component to the Student component.
App.jsx
import React from 'react';
import Student from './Student';
export default function App() {
return (
<>
<Student name="Damilare" age={30} isStudent={true} />
<Student name="Feyisayo" age={31} isStudent={true} />
<Student name="Inioluwa" age={4} isStudent={true} />
<Student name="Iteoluwa" age={1} isStudent={false} />
<Student /> {/* Uses defaultProps */}
<Student name="Bright" /> {/* Partial DefaultProps */}
</>
);
}
Rendering in DOM
index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
createRoot(document.getElementById('root')).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Takeaways
- Props: Immutable, passed from parent to child, and used for reusability.
- State: Mutable, manages dynamic behavior and is updated with this.setState().
- In modern React, hooks like useState make functional components equally capable of managing states, eliminating the need for class components.
Top comments (0)