What does props really mean in React.js, difference between props and state

in #reactjs2 years ago

pexels-kevin-ku-577585.jpg

In React, props (short for "properties") are a way to pass data from a parent component to a child component. Props are always passed down from the parent to the child, and the child can't change them.

Here's an example of using props in a simple React component:

20230106-123248.png

In this example, the MyComponent component expects to receive a name prop when it is used. The value of the name prop is then used within the component to render the greeting.

Here's how the MyComponent component could be used:

20230106-123300.png

In this example, the App component renders the MyComponent component and passes a name prop with the value "John". When this happens, the MyComponent component will render a greeting of "Hello, John!".

State, on the other hand, is a way to manage and store data within a React component that can change. Unlike props, a component can change its own state, but it should do so carefully, as changes to state can cause the component to re-render.

Here's an example of using state in a simple React component:

IMG_20230106_123523.jpg

In this example, the MyComponent component uses the useState hook to manage state. The state variable is count, and the setter function for count is setCount. The count variable is displayed in the component, and the Increment button increases the value of count by 1 when clicked.

The main difference between props and state is that props are passed down from the parent to the child, while state is managed within the component itself. Props are considered to be read-only, while state can be modified by the component.

Sort:  

Not at all like props, a part can change its own state, however it ought to do so cautiously, as changes to state can make the part re-render.