In this article, I will explain what is Props and State in React, and what is different between them. Before learning ReactJS, we should understand Props and State. This is basic for a newbie.
State is an object that holds some information in a component. The important point is whenever state object is changed, the component is re-rendering.
Let's take an example. We have a DownloadButton component, The label default is Download. Used useState hook to change the label to Processing when the user clicked.
import React, { useState } from 'react'; function DownloadButton() { const [btnLabel, setBtnLabel] = useState('Download'); const download = () => { setBtnLabel('Processing'); } return ( <div> <button onClick={download}>{btnLabel}</button> </div> ); }
Props are objects or values that are passed into a component. The main point is to pass data to your component and trigger State changes.
For example, we have 2 components that are ActionSession and DownloadButton. The DownloadButton component is children of ActionSession, it is received a value from the parent which is fileType. Then, the button label is changed after the fileType value is changed.
import React, { useState } from 'react'; interface DownloadButtonProps { fileType: 'csv' | 'excel'; } function DownloadButton({ fileType }: DownloadButtonProps) { const [btnLabel, setBtnLabel] = useState('Download'); const download = () => { setBtnLabel('Processing'); } return ( <div> <button onClick={download}>{btnLabel} - {fileType}</button> </div> ); } function ActionSession() { return <DownloadButton fileType='csv'/> }
Both Props and State are used to manage the data of a component but they are used in different ways and have different characteristics.
Props:
State:
Thank you for reading!
Next articles: