Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Lifting State Up in React

Introduction

In React, managing state across multiple components can be a challenge. Lifting state up is a common pattern used to manage state effectively by moving it to the closest common ancestor of the components that need it. This lesson will cover the concept, when to employ it, and provide an illustrative example.

What is Lifting State Up?

Lifting state up is the process of moving state from a child component to a parent component to allow the state to be shared or managed by the parent. This allows for better data flow and synchronization among sibling components.

Note: State should only be lifted when multiple components need to share the same state. Avoid lifting state unnecessarily as it can complicate the component hierarchy.

When to Lift State Up?

  • When two or more components need to share the same state.
  • When the state needs to be managed by a common parent component for better control.
  • When component data needs to be synchronized.

Step-by-Step Example

Let's look at a practical example where we have two components: TemperatureInput and BoilingVerdict. We will lift the state of the temperature from the TemperatureInput to their common ancestor Calculator.


import React, { useState } from 'react';

function Calculator() {
    const [temperature, setTemperature] = useState(''); // Lifting state up

    const handleChange = (e) => {
        setTemperature(e.target.value);
    };

    return (
        
); } function TemperatureInput({ temperature, onTemperatureChange }) { return (
Enter temperature in Celsius:
); } function BoilingVerdict({ celsius }) { if (celsius >= 100) { return

The water is boiling.

; } return

The water is not boiling.

; } export default Calculator;

Best Practices

  • Only lift state when necessary to avoid unnecessary complexity.
  • Keep your component hierarchy clean; aim for a simple parent-child relationship.
  • Use prop drilling wisely; in deep trees, consider using Context API for better state management.

FAQ

What if only one component needs the state?

If only one component needs the state, it is best to keep the state local to that component.

How can I manage state across multiple unrelated components?

You can use the Context API or a state management library like Redux to manage state across multiple unrelated components.

Is lifting state up the only way to share state?

No, you can also share state using context or global state management solutions.