I’m building a simple react application and I want to update the state of a component based on certain conditions. Currently, I’m using a hardcoded solution that works, but it seems too complicated and I want to know if there is a simpler way to achieve the same result.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
value: 'initial'
};
}
handleClick() {
this.setState((prevState) => {
if (prevState.count === 0) {
return { count: prevState.count + 1, value: 'clicked once' };
} else if (prevState.count === 1) {
return { count: prevState.count + 1, value: 'clicked twice' };
} else {
return { count: prevState.count + 1, value: 'clicked many times' };
}
});
}
render() {
return (
<div>
<p>{this.state.value}</p>
<button onClick={() => this.handleClick()}>Click me</button>
</div>
);
}
}
This works, but it’s not scalable and becomes hard to manage as the number of conditions increases.
2
Answers
You can use the conditional operator.
You are experiencing stress because your
value
state is an anti-pattern. It is a derivative ofcount
and should not have state of its own. That is to saycount
is your single source of truth –As a class-based component, that might look like this –