DEV Community

Ayoola Damilare
Ayoola Damilare

Posted on

My React Journey: Day 23

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

  1. Read-Only: Cannot be modified by the child component.
  2. Used in Functional and Class Components.
  3. PropTypes: Ensures props are of the correct data type during development.
age: PropTypes.number; // Throws a warning if a non-number is passed.
Enter fullscreen mode Exit fullscreen mode

4.DefaultProps: Provides default values for props when none are passed.

name: "Guest"; // Default value for the name prop.
Enter fullscreen mode Exit fullscreen mode

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,
};
Enter fullscreen mode Exit fullscreen mode

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

  1. Can only be used in Class Components (in older React).
  2. Mutable: Updated using this.setState().
  3. 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 */}
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
);
Enter fullscreen mode Exit fullscreen mode

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)