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
In React build in object which allows component to manage data that can change over time, Example of javascript variables, state triggers re-renders
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
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
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