The difference between props and state in React

Natalia Wit
2 min readAug 23, 2020

--

When I first started learning React, the hardest thing was grasping the concept between props and state. I think that is a common thing for any beginner trying to grasp the fundamentals of React. As we know most applications are dynamic and change over time and that’s where the state comes into an advantage. State allows React components to change their output in response to user actions, network responses, etc., as on the other hand props never change.

Props

Reactpropsare used to customize Components when they are being created and as well as giving them different parameters. It is important to note that props have one important feature which allows them to be passed by a parent component to its child components. This allows us to create components that can be customized with a new set of props. We can assign default props to a component in a case where a prop isn't passed. Since props are passed down and in, they cannot change. Any React component that uses props and not state is a “pure” component. A pure component will always render the same output given at the same input.

State

There will be times when we need to use some kind of data that is going to change over time and this is a case where the state comes into play. Usually, states are initialized right after defining your class unless you’re using hooks. when you initialize your state that will be the initial data. A state can be updated by using the inbuilt setState() helper function. Keep in mind that states will be managed within a component. In the above example, notice that setState() takes a function and the reasoning behind that is that setState can run asynchronously. It will take a callback function rather than updating the state directly. Within the callback function, you can see that we have access to prevState which will contain the previous state — even if the state has already been updated somewhere else. setState updates the state object and rerenders the component automatically.

Conclusion

While props and state both hold information relating to the component, they are used differently and should be kept separate. Remember that props are READ ONLY and the state represents the parts of the app that can always change.

--

--

No responses yet