React Props and State: A Complete, Easy-to-Follow Tutorial
2 min read

React Props and State: A Complete, Easy-to-Follow Tutorial

In this tutorial, I'll walk you through the essentials of React props and state, making it simple and easy to understand for anyone. Let's dive in!

React Props

React props (short for "properties") allow you to pass data from a parent component to a child component. They help create reusable and maintainable code. Here's an example of how to use props:

import React from 'react';

const Greeting = (props) => {
  return <h1>Hello, {props.name}!</h1>;
};

export default Greeting;

In the parent component, you can pass data to the Greeting component like this:

import React from 'react';
import Greeting from './Greeting';

const App = () => {
  return (
    <div>
      <Greeting name="John" />
    </div>
  );
};

export default App;

React State

State is used to manage data that changes over time within a component. It is an essential concept in React, allowing you to create dynamic and interactive user interfaces. Here's a simple example of how to use state in a functional component using the useState hook:

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
};

export default Counter;

In this example, I used the useState hook to manage the count state and the setCount function to update it.

Passing State as Props

You can also pass state from a parent component to a child component using props. Here's an example:

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

const App = () => {
  const [text, setText] = useState('Hello, world!');

  return (
    <div>
      <Display message={text} />
    </div>
  );
};

export default App;

In this case, the text state is passed as a prop to the Display component.

Conclusion

Understanding React props and state is crucial for creating dynamic and interactive applications. In this tutorial, I covered the basics of using props and state in React, as well as how to pass state as props between components. By mastering these concepts, you'll be well on your way to building efficient, maintainable React applications.