React: Props vs State

Brian Li
3 min readJan 22, 2021

--

For the longest time, I had the most trouble with Props and State when it came towards React. Coming from a very minimal coding background, I had no way of really knowing how similar a prop and state are to different languages and their concepts.

Props

What is a prop? Props, by definition, is a special keyword in React, “ which stands for properties and is being used for passing data from one component to another.” In essence, props are very much like arguments in a function whereas components are conceptually functions. It’s also important to remember that props are passed in a uni-directional flow, meaning data is being passed down from the parent component to its nested child components. With that being said, props are also read-only so data from the parent should not be changed by the child.

From the example above, we can see how the props are being passed down into our Subject child components with prop names of “Math” and “History”. Notice how the props are not being modified, allowing us to create a new component with a new set of props every time.

State

While props are passed and remain fixed during the lifecycle, what happens if you want to use data that you know is going to change overtime? This is where state comes in. State, which should be private, is a object that allows component to create and manage their own data. Data can never be passed in state like props can, but they supplement data internally meaning each component can have their own state with their own property values.

What if I want to change the state? Well React uses a special method called setState() which re-renders the user interface in response to event handlers and clickers.

The previous example explains that whenever we click on the onClick button, we are re-render the state by using setState() to change the score by 1. Remember that setState() only re-render the state of that specific component and not the entire DOM window.

There is so much more props and state can be used for but these are the very basics for React. Once Redux is implemented in your code, state is automatically created for you and you won’t have to worry about updating the state as much.

--

--

No responses yet