DEV Community

Selahaddin Osmanoglu
Selahaddin Osmanoglu

Posted on

Part 5: Managing Component State – Lifting State and Data Flow

Welcome to Part 5 of the React for Beginners series!

In the last part, we learned how to render lists. Now let’s talk about how to share data between components and how to manage it in a clean and predictable way.

This post introduces a powerful concept: lifting state up.


🔄 One-Way Data Flow in React

React follows a simple principle:

Data flows down from parent to child components via props.

If a parent has state, it can pass it down to children. But children can’t directly change the parent’s state.

Let’s explore how this works.


🧪 Example: Two Sibling Components Need Shared State

Suppose we want:

  • An input component where a user types a name
  • A display component that shows the current name

These are sibling components. But they need to share the same state.


🧠 Lifting State Up

The solution is to:

  1. Store the state in the common parent
  2. Pass the state and updater function down via props

Let’s build it!


NameInput.jsx

function NameInput({ name, setName }) {
  return (
    <input
      type="text"
      value={name}
      onChange={(e) => setName(e.target.value)}
      placeholder="Enter your name"
    />
  );
}

export default NameInput;
Enter fullscreen mode Exit fullscreen mode

NameDisplay.jsx

function NameDisplay({ name }) {
  return <p>Hello, {name || 'stranger'}!</p>;
}

export default NameDisplay;
Enter fullscreen mode Exit fullscreen mode

App.jsx

import { useState } from 'react';
import NameInput from './NameInput';
import NameDisplay from './NameDisplay';

function App() {
  const [name, setName] = useState('');

  return (
    <div>
      <h1>Lifting State Up</h1>
      <NameInput name={name} setName={setName} />
      <NameDisplay name={name} />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

✅ Now both components stay in sync by using the same state from their parent.


🚫 The Prop Drilling Problem (Preview)

When you pass state through many levels of components, it can become messy.

This is called prop drilling.

You’ll see this in larger apps, and we’ll solve it later with Context or state management libraries (covered in Part 11).


✍️ Challenge for You

Create a TemperatureConverter component:

  • An input field where users enter a Celsius temperature.
  • A sibling component that shows the value in Fahrenheit.
  • Store the state in the parent and pass it down.

(Hint: °F = °C × 1.8 + 32)


✅ Summary

  • React uses one-way data flow: parents pass data to children via props.
  • To share state between components, lift the state up to their common parent.
  • Pass both the state and updater function as props.

🔜 What’s Next?

In Part 6, we’ll explore useEffect and side effects — perfect for fetching data, timers, and more.

You're now thinking like a React developer! 🧠⚛️

Top comments (0)