DEV Community

Evan Charalampidis
Evan Charalampidis

Posted on

React Props vs State

πŸ‘‹ Introduction

React, a popular JavaScript library for building user interfaces, utilizes two core concepts for managing data within components: props and state. Understanding the differences between these two is fundamental to building robust and maintainable React applications.

πŸš€ Getting Started

Props are read-only, immutable values passed from parent to child components. They are akin to function parameters, allowing data to flow in a one-way direction. Here's a simple example:

// ParentComponent.js
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const data = "Hello from Parent!";
  return <ChildComponent message={data} />;
}

// ChildComponent.js
function ChildComponent(props) {
  return <div>{props.message}</div>;
}
Enter fullscreen mode Exit fullscreen mode

In contrast, State represents mutable data local to a component, managed internally. It is used to handle dynamic data that can change over time. Here's a snippet illustrating state usage:

// Counter.js
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

🏁 Conclusion

In summary, in React function components, props are for passing data from parent to child components, while state is for managing a component's internal, mutable data. Combining these concepts effectively allows you to create dynamic and interactive React applications.

Github: @imevanc
Twitter: @imevancc

Top comments (0)