While working on a react project a question kept coming up that I seem to not be able to put into words. Whats the difference between state and props? What do each do within react? Leaving me confused each time I was asked I decided to attempt to put it into words what are the main differences to help not only myself but someone else out there looking for the answer.
So what is Props? Props is short for properties, what props do is that they are passed into a component. You have information within them to be used into different components when needed. Think about it being like an argument being passed into a function, it holds the data that was given to them for them to be used and displayed. Important thing to not is that props should not be changed, they are “pure” you dont want to mutate them because unlike “pure” props, you will have a different output which will make testing very difficult. Those are the basics with props; When it comes to talking about state theres a little more that comes with it.
Ok, so with props theres not much going on, its pretty self explanatory on their use. With State however, they are similar in that they hold information about the component. But they handle that information differently. A component does not have a state with it automatically, so when do we use state at all? We need to use state for rendering the component itself, it can update, create and use the state.
Some main differences between state and prop is that state is actually made within the component, it could receive data from props but also have hard code within it. Such as having a like button being set to zero. Unlike our pure props, state is changeable. We would have the state have the likes set to zero, but then we would use setState have the likes incremented every-time a button was clicked by one. Sounds confusing to talk about, but luckily I have done something like this before. Below I have code for it done within a js file.
Thats pretty much it for the main differences that I’ve found between state and props. Hope you found it as helpful as me trying to explain the differences! Once more, we’ll spend a moment to go over the things that Ive talked about; props and states hold information for the component, but they are used differently and should be kept separately. Props hold information from the from the parent component and should not be changed. State hold private information for the component to initialize, change and used on its own. That sums things up pretty well id say! Thank you for taking the time to read my blog post and have a wonderful day!