Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

componentWillReceiveProps, componentDidUpdate for React Hook

I run into two challenges:

  • Even if, as per React guideline, derived state is discouraged, but some edge cases still need it.
    In terms of a functional component with React Hook, What is the equivalent implementation with React Hook, If I do need derived state which in class component, will be updated in componentWillReceiveProps on every parent render

see below code sample:

class App extends Component {   constructor(props) {     super(props);     this.state = {       count: props.count > 100 ? 100 : props.count,     }    }    /*What is the equivalent implementation when React Hook is used here componentWillReceiveProps*/   componentWillReceiveProps(nextProps) {     if (nextProps.count !== this.props.count) {       this.setState({         count: nextProps.count > 100 ? 100 : nextProps.count       });     }   }    render() {     return ( <       div > {         this.state.count       } <       /div>     );   } }  export default App;
  • As for componentDidUpdate, componentDidUpdate has its counterpart when React Hook is used, you have to use it like,

      React.useEffect(() => {     return () => {       };   }, [parentProp]); 

    the Second param for useEffect makes sure code is executed only when prop changes, but what if I want to do respective tasks based on multiple respective props changes? how to get it done with useEffect?

see below code sample:

class App extends Component {     /*What is the equivalent implementation when functional component with React Hook is used here */   componentDidUpdate(prevProps, prevState) {     if (prevProps.groupName !== this.props.groupName) {       console.log('Let'         's say, I do want to do some task here only when groupName differs');     } else if (prevProps.companyName !== this.props.companyName) {       console.log('Let'         's say, I do want to do some different task here only when companyName differs');     }    }     render() {     /*for simplicity, render code is ignored*/     return null;   } }  export default App;
like image 924
Deng Zhebin Avatar asked Feb 23 '19 16:02

Deng Zhebin


1 Answers

The react hook equivalent to the old componentWillReceive props can be done using the useEffect hook, just specifying the prop that we want to listen for changes in the dependency array.

I.e:

export default (props) => {      useEffect( () => {         console.log('counter updated');     }, [props.counter])      return <div>Hi {props.counter}</div> } 

For componentDidUpdate just by omitting the dependency array, the useEffect function will be called after every re-render.

I.e:

export default (props) => {      useEffect( () => {         console.log('counter updated');     })      return <div>Hi {props.counter}</div> } 
like image 71
fgonzalez Avatar answered Sep 22 '22 13:09

fgonzalez