DEV Community

Cover image for Mastering Props and State Management in React
Sayuj Sehgal
Sayuj Sehgal

Posted on

Mastering Props and State Management in React

In React, props and state are two important concepts that help manage data in your application.

Props (short for properties) are a way of passing data from parent components to child components. They are read-only and cannot be changed by the component receiving them.

State, on the other hand, is a data structure that starts with a default value when a component mounts and gets mutated in time (mostly due to user events). It's used for mutable data, or data that will change.

Let's look at an example that uses both props and state:

import React, { useState } from 'react';

// Parent Component
const App = () => {
  const [state, setState] = useState("Hello from Parent!");
  const changeMessage = () => {
    setState("State changed in Parent!");
  }
  return (
    <div>
      <button onClick={changeMessage}>Change Message</button>
      <ChildComponent message={state} />
    </div>
  );
};

// Child Component
const ChildComponent = (props) => {
  return <p>{props.message}</p>;
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In this example, the App component is the parent component. It has a state variable state that is initially set to "Hello from Parent!". The useState hook is used to create this state variable and the function to update it (setState).

The ChildComponent is a child component that receives the state variable from App as a prop (message). It displays this prop in a paragraph element.

The changeMessage function in the App component changes the state when the button is clicked. Since the ChildComponent is using this state as a prop, it will also update to reflect this change. This is an example of how state and props can be used to manage and pass data in a React application.

Choosing the Right Tool for the Job

Props: Use props for passing simple, static data down the component tree.

State: Use state for managing internal data that changes within a component.

Remember the Key Points:

  • Props and state are the foundation for data flow and interactivity in React.

  • Props are one-way data flow from parent to child.

  • State manages internal data within a component.

  • Choose the right tool based on your data needs and complexity.

Conclusion:

Understanding the dynamics of props and state management is foundational to mastering React. As you explore more complex applications, these concepts will be your allies in creating modular, reusable, and interactive components. Stay tuned for the next installment in the React 101 Learning Series! Happy coding!

If you like this blog, you can visit my blog sehgaltech for more content.

Top comments (0)