React’s state vs props

Props

Props also known as properties. Props is what allows us to pass values into components and between components. Props are passed down from the parent component. In order to pass props down to a component, one adds it in the render function as an attribute.

Another important note is that the value of props is passed through JSX in curly braces {}. Props can be any value such as objects, arrays, strings, functions, etc. One of the nice things about props is that it allows our react components to be dynamic and re-usable. Otherwise, we’d be stuck with hard coded data and that defeats all of the benefits of react. The limitation with props is that in order for props to change, the parent component must send it new props.

Here is an example of how props is passed down.

token is a prop of ListForm

In the above example, the parent component is MainComponent and it needs to pass data down to the child component which is ListForm. The child component has been assigned a prop of token.

State

First and for most, state is a plain JavaScript object. State is the data in your component that is mutated. A component’s state can changes during the components life. State is created and managed internally, within a component. State is used when its expected that some values will change, i.e. clicking a like button, entering information in a form, etc. State is initially set up in the base constructor.

Here is an example of how we set up state.

state in the constructor inside a class component
state in a class component

Remember, state changes when a user triggers some event in the browser. In order for the state to make updates, setState() is used. State should not be modified directly but rather with setState().

See the example below.

setState() used to update username and password attributes

State holds the initial data. When state needs to be updated, React immediately re-renders the DOM specific to that change. The setState() method is what triggers the DOM to re-render.

State used to only be available in class components and not in functional components. Functional components are known for being stateless components, however, since React introduced hooks it is possible to incorporate state.

Props is external to component and is passed down from parent component. A child component cannot directly change props.

State is internal to a component and updated by the user triggering an event in the browser. The state is updated through a method called setState(). State cannot be accessed outside the component, it is private to the component.

Props is used to pass down data, and state is used for managing data.

Hopefully, this article has helped to clarify the key difference between React state and props.

Happy coding…

Full stack web developer