I got confused to understand a Different between Classes & Functions in React JS

Viewed 61

I got confused to understand a Different between Classes & Functions in React JS .

as you can see I wrote a code that show the user whom I followed with Class and function , please check it . Consider this component:

function ProfilePage(props) {
  const showMessage = () => {
    alert('Followed ' + props.user);
  };

  const handleClick = () => {
    setTimeout(showMessage, 3000);
  };

  return (
    <button onClick={handleClick}>Follow</button>
  );
}

It shows a button that simulates a network request with setTimeout and then shows a confirmation alert. For example, if props.user is 'Dan', it will show 'Followed Dan' after three seconds. Simple enough.

The same code but in class component

class ProfilePage extends React.Component {
  showMessage = () => {
    alert('Followed ' + this.props.user);
  };

  handleClick = () => {
    setTimeout(this.showMessage, 3000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

The App.js file

import ProfilePageFunction from './ProfilePageFunction';
import ProfilePageClass from './ProfilePageClass';

class App extends React.Component {
  state = {
    user: 'Dan',
  };
  render() {
    return (
      <>
        <label>
          <b>Choose profile to view: </b>
          <select
            value={this.state.user}
            onChange={e => this.setState({ user: e.target.value })}
          >
            <option value="Dan">Dan</option>
            <option value="Sophie">Sophie</option>
            <option value="Sunil">Sunil</option>
          </select>
        </label>
        <h1>Welcome to {this.state.user}’s profile!</h1>
        <p>
          <ProfilePageFunction user={this.state.user} />
          <b> (function)</b>
        </p>
        <p>
          <ProfilePageClass user={this.state.user} />
          <b> (class)</b>
        </p>
        <p>
          Can you spot the difference in the behavior?
        </p>
      </>
    )
  }
}

Try this sequence of actions with both buttons:

1 Click one of the Follow buttons. 2 Change the selected profile before 3 seconds pass. 3 Read the alert text.

With the above ProfilePage function, clicking Follow on Dan’s profile and then navigating to Sophie’s would still alert 'Followed Dan'. With the above ProfilePage class, it would alert 'Followed Sophie'

But why is That ??

try it here : https://codesandbox.io/s/pjqnl16lm7?file=/src/index.js:62-1024

0 Answers
Related