DEV Community

jpabloc17
jpabloc17

Posted on

"Props and States in React JS"

React is a JavaScript library that we can use to build User Interfaces and separate the structure of the app into components. When working with React, we have different ways to pass data between parent and child components: Props and state.

What is a component?

A component is basically a function that takes data (props) as an argument and returns JSX. Components are dynamic and enable us to think about each piece in isolation, helping us keep our code organized.

Props (Properties):

Props are pieces of information passed from a parent component to a child component as objects that store the values of attributes of a tag. They can hold any kind of data, such as strings, numbers, objects, and even functions. They can be accessed in the child component as parameters of the component function.

Image of porps

State:

A state is essentially a variable used to contain information about the component that can change over the time as users interact with the application. State provides us with a way to maintain and update information within a component without requiring its parent to send the new information. The "change in the state" can happen as a response to user actions or system events. To use state, first, we need to import a hook from React called "useState." The useState hook will return an array with two variables inside of it: a reference to the current value and a set function so we can update that value."

Image of useState

In this example, we have a Counter component that uses state to Increment the value when the button is clicked, the state changes, and the component re-renders every time the we updated count.

In conclusion, props can pass data from parent to child components, while states can manage dynamic data within a component, allowing the user to update it while interacting.

Top comments (0)