I have MyComponent using setData() to write data in state and getData() to read the state. Is it best practice in React ? It works fine for me but not sure if what I am doing is the simplest possible way, please advice
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
setData(){
this.setState({data:"123"});
}
getData() {
console.log(this.state.data); // 123 OK !!!
}
componentDidMount() {
this.setData();
}
componentDidUpdate() {
this.getData();
}
render() {
return (
<div>
{this.state.data} // 123 OK !!!
</div>
);
}
}
There is absolutely no reason to do this.
Just use this.state.data
wherever you need to use it.
If you want to use the state data in a child component, then pass it as a prop and you may also pass a function to the child component that changes the state of the parent component.
(source)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With