Loading...
Loading...

React Lifting State

Lifting state up in React involves moving the state to the nearest common ancestor component so multiple child components can access and update that state. This allows data sharing across sibling components and simplifies state management.

1. Why Lift State Up?

React encourages moving state up to the closest common ancestor of components that need to share it. This pattern is essential for making sure all components remain in sync when they rely on shared data.

2. Example of Lifting State Up

Consider a scenario where you have two components, TemperatureInput and BoilingVerdict, and you want to calculate whether a temperature (in Celsius) would cause water to boil.

import React, { useState } from 'react';

function BoilingVerdict({ celsius }) {
    return <p>{celsius >= 100 ? 'The water would boil.' : 'The water would not boil.'}</p>;
}

function TemperatureInput({ temperature, onTemperatureChange }) {
    const handleChange = (event) => {
        onTemperatureChange(event.target.value);
    };

    return (
        <fieldset>
            <legend>Enter temperature in Celsius:</legend>
            <input value={temperature} onChange={handleChange} />
        </fieldset>
    );
}

function Calculator() {
    const [temperature, setTemperature] = useState('');

    return (
        <div>
            <TemperatureInput
                temperature={temperature}
                onTemperatureChange={setTemperature}
            />
            <BoilingVerdict celsius={parseFloat(temperature)} />
        </div>
    );
}

In this example, the Calculator component holds the state for temperature and passes it to both TemperatureInput and BoilingVerdict. This structure allows these sibling components to access and update the same state.

3. Breaking Down the Components

  • BoilingVerdict: Displays whether the water will boil based on the Celsius temperature passed as a prop.
  • TemperatureInput: Takes the temperature as a prop and updates it using the onTemperatureChange callback.
  • Calculator: Maintains the temperature state and provides it to both child components.

4. Using Callback Functions

In this pattern, Calculator passes a callback function, setTemperature, to TemperatureInput. When the input changes, this callback updates the state in Calculator, which in turn updates both TemperatureInput and BoilingVerdict with the latest data.

5. Summary

By lifting state up, you can centralize the data management for multiple components, allowing them to work with shared data and stay in sync. This technique helps maintain predictable state flow and ensures that your components are consistently up-to-date with shared data.

0 Interaction
2.3K Views
Views
12 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home