Do you know about Props and State in React??

Tram Ho

If you are a programmer using React, you are probably familiar with using Props or State in components.

But do you know the difference between them?

If not, let’s find out together.

Props

  • Props is an object that holds the values ​​of a tag’s attributes and is how components receive values ​​passed in from the outside.

For example:

  • Here we have passed the name property into the XinChao component’s props .
  • Each component’s property will correspond to an attribute of the tag and the value of that attribute will be passed to the props property.
  • You can change the Props using setProps or replaceProps but it is not recommended that you use them because React has a rule that is pure function: do not change the input value and always return 1 type of format ( Props are Read-Only)

State

  • Just like props , state also stores information about the component, but stores the dynamic data of a component.
  • State is dynamic data, it allows a component to track information that changes between renders and make it interactive.
  • State can only be used within a component that spawned it.
  • If the component needs to manage state, it should be created in a class component rather than a function component.

For example:

  • With the above example, when we enter the page at 22:20:58 , we will get the result

image.png

  • And every time we f5 the time will change.
  • To keep the time up to date, you can learn more about lifecycle methods .

Props and State

Alike

  • Both to be the basic object in React and when changing the value will perform render .

Other

PropsState
Data ManagementPassing data to component is like passing param in functionmanaged inside the component
Change data in componentNo (due to data being passed in)Yes (due to being managed inside the component)
Change data from parent componentHaveAre not

Ending

  • Above is what I know about props and state in React hope it will help everyone.
  • Thank you everyone for reading my post if you find it useful, please upvote for me!
Share the news now

Source : Viblo