Lifecycle-methods, part - componentDidMount

Hello,

In this exercise setInterval() function presented:
https://www.codecademy.com/paths/web-development/tracks/front-end-applications-with-react/modules/react-102-lifecycle-methods-u/lessons/component-lifecycle-methods/exercises/component-did-mount

Could someone explain what would be the difference between:

componentDidMount() {
const oneSecond = 1000;
setInterval(() => {this.setState({ date: new Date() });}, oneSecond);
}

AND

componentDidMount() {
const oneSecond = 1000;
setInterval(this.setState( {date: new Date()}), oneSecond);
}


I understand that setInterval takes two parameters function and delay - setInterval( func , [ delay , arg1 , arg2 , …]);
If setState is a function, so why we need to do a call back function here?

Thank you,

Hello, and welcome to the forums!

As you mentioned, setInterval takes a function as the first argument. The difference between these:

() => {this.setState({ date: new Date() });}
this.setState( {date: new Date()})

is that the first one is creating an arrow function that calls the block of code, while the second one is immediately calling this.setState() and returning the value (if any) that gets returned by calling it. If you had only written this.setState, then it would remain a function and not be evaluated, but then it wouldn’t have the function arguments that you want to send it.

Consider the following:

console.log(() => 4);
//would print: [Function]

console.log(4);
//would print: 4

A more expanded example with other ways to define the function too:

const functionOne = () => 1;

const functionTwo = function() {
  return 2;
};

function functionThree() {
  return 3;
}
console.log(functionOne);
console.log(functionTwo);
console.log(functionThree);

would print the following since the functions weren’t called:

[Function: functionOne]
[Function: functionTwo]
[Function: functionThree]
console.log(functionOne());
console.log(functionTwo());
console.log(functionThree());

would call the functions, so it would print the values:

1
2
3
1 Like

Thanks for the great explanation. Now, this part is clear for me :wink:

1 Like