top of page
Logo der Online Agentur mdwp

Concept of Lifting State Up

React JS is a popular JavaScript library used for building user interfaces, particularly single-page applications. The term "Lifting State Up" in React JS refers to the process of moving the state of a component to its common ancestor or parent component if more than one child components are sharing the same data.

This method is useful because, in React, you cannot directly communicate between two components that do not have a parent-child relationship. You can achieve this indirectly by lifting state up i.e., by moving shared state to their nearest common ancestor. This makes it possible to share the state data across multiple components resulting in a easy state management.

Here is a simple code snippet illustrating Lifting State Up:

```jsx
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
sharedData: "",
};
this.updateData = this.updateData.bind(this);
}

updateData(value) {
this.setState({
sharedData: value
});
}

render() {
return (
<div>
<Child1 data={this.state.sharedData} onDataUpdate={this.updateData} />
<Child2 data={this.state.sharedData} onDataUpdate={this.updateData} />
</div>
);
}
}

function Child1(props) {
return (
<div>
<input value={props.data} onChange={e => props.onDataUpdate(e.target.value)} />
</div>
);
}

function Child2(props) {
return (
<div>
<p>{props.data}</p>
</div>
);
}
```

In the code above, `ParentComponent` has two child components: `Child1` and `Child2`. The state with key `sharedData` is declared in the `ParentComponent`, and it is then passed to the child components through props. `Child1` component changes the state via an input element, and `Child2` component displays the updated state. Here, we've lifted the state up to the `ParentComponent`, allowing `Child1` and `Child2` to share the data and stay in sync.

bottom of page