React JS Tutorial: State vs Props šŸŽÆ

beginner
8 min

React JS Tutorial: State vs Props šŸŽÆ

Welcome to the React JS tutorial where we'll dive into understanding the core concepts of State and Props! These two are fundamental building blocks in a React component. Let's get started! šŸš€

What are State and Props in React? šŸ“

In simple terms, State is a data container within a React component, while Props are the data passed from a parent component to a child component.

State šŸ’”

  • State is an object that stores the data specific to the component.
  • State can be modified internally by the component.
  • State changes trigger a component re-render.
javascript
import React, { Component } from 'react'; class MyComponent extends Component { constructor(props) { super(props); this.state = { count: 0 }; } incrementCount = () => { this.setState({ count: this.state.count + 1 }); } render() { return ( <div> Count: {this.state.count} <button onClick={this.incrementCount}>Increment</button> </div> ); } }

šŸ’” Pro Tip: Use this.setState to update the state.

Props šŸ’”

  • Props are passed from a parent component to a child component as an object.
  • Props are immutable and cannot be modified by the child component.
  • Props changes do not trigger a re-render of the child component. Instead, the child component receives the new props and re-renders.
javascript
function MyChildComponent(props) { return ( <div> This is a child component with prop: {props.myProp} </div> ); } function App() { return ( <MyChildComponent myProp="Hello, World!" /> ); }

State vs Props: Key Differences šŸ“

  • State is component-specific, while Props are component-external.
  • State is mutable and can be changed within the component, while Props are immutable and passed as read-only.
  • Changes in State trigger a component re-render, while changes in Props trigger a re-render of the child component.

Quiz: Identify the Correct Statement šŸŽÆ

Quick Quiz
Question 1 of 1

What is the main difference between State and Props in React?

That's it for our first lesson on React JS! By understanding State and Props, you have laid a strong foundation for building React components.

Stay tuned for our next lesson, where we'll dive deeper into working with the state and handle state changes efficiently using React Hooks! šŸ“šŸ’”šŸš€