Lifecycle-methods, part - componentDidMount


In this exercise setInterval() function presented:

Could someone explain what would be the difference between:

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


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]

//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;

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

[Function: functionOne]
[Function: functionTwo]
[Function: functionThree]

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

1 Like

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

1 Like