State and Props: The Building Blocks of React

Written on 30-Nov-2024

Table of Contents

It's being while from blog side, In this blog going to cover complete understanding about State and props in the react and when to use state, when to use props

What is State in React?

In React build in object which allows component to manage data that can change over time, Example of javascript variables, state triggers re-renders

Features of State

  1. Mutable : In react state can be updated using useState hook in function component
  2. Reactive : Updates to state automatically refresh the UI.

State Example

    import React, { useState } from "react";
    const Counter = () = {
        const [count,setCount] = useState(0);
        const increment = () => setCount(count + 1);
     return(
        <div>
            <h1>Counter : {count}</h1>
            <button onClick={increment}>Increment</button>
        </div>
     );
    }
    export default Counter;

From the example code useState hook initializes with default value of 0 and the setCount function updates the state and triggers a re-renders

What is Props

Props is used to pass the data from one component to another component, Example like passing data from parent component to child component, Props which are used only for read-only which its cannot modified from receiving end

Featurs in Props

  1. Immutable :
  2. Resuable Component:

Props Example

    const Greeting = (props) => {
      return <h1>Hello, {props.name} </h1>
    }

    const App = () => {
     return(
        <div>
            <Greeting name="Naveen" />
            <Greeting name="Arya" />
        </div>
     )
    }
 export default App;

From the example code Greeting component receives a name prop and displays it dynamically, App Component resues greeting with different props as Naveen Alice