Skip to content

Instantly share code, notes, and snippets.

@nirsky
Last active June 9, 2020 08:51
Show Gist options
  • Save nirsky/6021d4a8c1c728872348aefa2adcd0eb to your computer and use it in GitHub Desktop.
Save nirsky/6021d4a8c1c728872348aefa2adcd0eb to your computer and use it in GitHub Desktop.
//Class
componentWillReceiveProps(nextProps) {
if (nextProps.count !== this.props.count) {
console.log('count changed', nextProps.count);
}
}
//Hooks
//Printing 1st iteration:
useEffect(() => {
console.log('count changed', props.count);
}, [props.count])
//Skipping first iteration (exactly like componentWillReceiveProps):
const isFirstRun = useRef(true);
useEffect (() => {
if (isFirstRun.current) {
isFirstRun.current = false;
return;
}
console.log('count changed', props.count);
}, [props.count]);
//Class
componentDidUpdate() {
console.log('Just updated..');
}
//Hooks
useEffect(() => {
console.log('Just updated...');
})
@borm
Copy link

borm commented Jun 8, 2020

It`s not working

//Hooks
useEffect(() => {
    console.log('count changed', props.count);
}, [props.count])

https://jsfiddle.net/h6pudszo/3/

look at console

"count changed", 0
"count changed", 1

@nirsky
Copy link
Author

nirsky commented Jun 9, 2020

Hey @borm , by not working I guess you mean that it prints the first iteration, while componentWillReceiveProps will skip it.
You’re actually right on that.
There’s a small workaround to skip the first render using useRef , this StackOverflow question shows an example:

const isFirstRun = useRef(true);
useEffect (() => {
    if (isFirstRun.current) {
        isFirstRun.current = false;
        return;
    }
    console.log('count changed', props.count);
}, [props.count]);

Sorry for the confusion, updated the gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment