Address
304 North Cardinal St.
Dorchester Center, MA 02124
Work Hours
Monday to Friday: 7AM - 7PM
Weekend: 10AM - 5PM
React Props vs States is an essential concept in ReactJS used to manage data and control the behavior of components. Props and States are both used in React to manage data, but they serve different purposes and have different characteristics which we will discuss further.
Props, short for Properties, are used to pass data from a Parent Component to a Child Component. Props are read-only meaning that they cannot be modified by the Child Component. Instead, the Child Component can use props to display or trigger events.
In React, You can pass data between components using props. In this way, Parent Component passes data to Child Component. For Example:
<strong>parent</strong>
and <strong>child</strong>
in a file name props.jsprops.js
import React from "react";
function Parent() {
const name = "Devcribe";
return (
<div>
<Child name={name} />
</div>
);
}
function Child(props) {
return (
<div>
<p>{props.name}</p>
</div>
);
}
export default Parent;
App.js
import React from "react";
import Parent from "./props";
function App() {
return (
<div>
<Parent />
</div>
);
}
export default App;
npm start
State, on the other hand, is used to manage data within a component. Unlike props, the state can be modified by the component itself. When the state of a component changes, React will automatically re-render the component and update the UI.
In React, you can manage the component state using the ‘useState’ hook. The ‘useState’ hook is a built-in React hook that allows you to add a state to a functional component. For Example:
<strong>StateManagment.js</strong>
<strong>Counter()</strong>
function in it and the following code.StateManagment.js
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>You Clicked the button {count} times.</p>
<button onClick={handleClick}>Click</button>
</div>
);
}
export default Counter;
App.js
import React from "react";
import Counter from "./StateManagment";
function App() {
return (
<div>
<Counter />
</div>
);
}
export default App;
React Props vs States, both are used in React to manage data, but they serve different purposes and have different characteristics, such as
<strong>parent component</strong>
to a <strong>child component</strong>
.<strong>child component</strong>
.<strong>child component</strong>
.<strong>parent component</strong>
will trigger a re-render of the <strong>child component</strong>
That’s all to understand React Props vs States in ReactJS. I hope it will be a quite useful tutorial to understand how to implement Props and States as well as how it works.
Also, check out React Component in 5 easy steps. If your want to learn more about ReactJS, you can follow all the ReactJS tutorials starting from “Introduction to React” on devcribe.com. Happy Coding!