Let’s see how React handles data. It’s done in 2 ways using state and the props.
Props
One of the method is using properties( a.k.a Props )
Lets see how to handle data using props:
export const Parent : () => {
const name = "John";
const address = "address";
return(
<Child
name = {name}
address = {address}
></Child>
)
};
interface IChild {
name : string;
address : string;
}
import React, FC from "react"; // FC : FunctionComponent
export const Child : FC<IChild> = (props) => {
const fathersName = props.name;
const address = props.address;
};
State
You can think of a state as a shopping cart, where you add/remove/modify items before the purchase.
In the same way here React has state where you can add/remove/modify data for a particular component or within the state of entire application.
import React, {useState} from "react";
export const SampleFuncComponent : () => {
const [name,setName] = useState("");
const [flag,setFlag] = useState()<boolean>;
const userName = "John Doe";
const userActive = true;
setName(userName);
setFlag(userActive);
// now you can use the state variables around this code
const completeName = name; // "John Doe"
if(flag){
const active = flag; // true
}
};
Summary
In this article, we learnt how react handles data between the components, two ways to transfer data using state and props.
Please let us know in the comments below about your thoughts and queries.
Hope you liked it !