Reputation: 927
I try to make my code clean. I have two options.
1st
state = {
onChange: this.props.onChange,
}
2nd
state = {
onChange: null,
}
componentDidMount(){
this.setState({
onChange: this.props.onChange,
});
}
I would like to use 1st in my code as it looks neater. But I am unsure is works like 2nd? Kindly advise.
Upvotes: 0
Views: 69
Reputation: 754
Ideally, you should refrain from initializing state with props value, it's an anti-pattern. Read more about it here
Additionally, if you have some value that already exists in props object, you should try using that value directly in the component where ever you can and avoid duplicating the same values in Parent and Child component.
But in case for some reason you have to have the same data in your Child component as well, then, in that case, refer to the code snippet below.
state = {
onChange: null
}
componentDidMount() {
this.changeHandler();
}
//abstracted helper function, could be reused from other life cycle methods if need be
changeHandler = () => {
this.setState({
onChange: this.props.onChange || null
})
}
If this.props.onChange exists, local state value will be updated, else will be set to null. Hope this gives you some perspective, let me know if you are still confused.
Upvotes: 1