Hacia la desaparición (o no) de los “Class Components” en React

Qué supone la aparición de los React Hooks

Image for post
Image for post

¿Pero qué problema hay con los Class Components?

Hooks en React 16.7

Image for post
Image for post

UseState

import React, { useState } from "react";import ReactDOM from "react-dom";const MyAwesomeFuncComponent = props => { // Aquí viene la magia const [name, setName] = useState(); return (   <div>     <h1>Hello {name}</h1>     <input type="text" onChange={e => setName(e.target.value)} />   </div>  );}; export default MyAwesomeFuncComponent;
import React, { useState } from "react";import ReactDOM from "react-dom";const MyAwesomeFuncComponent = props => {  const [name, setName] = useState();  const [age, setAge] = useState(18);  return (    <div>      <h1>Hello {name}, your age is: {age}</h1>      <input type="text" onChange={e => setName(e.target.value)} />      <input type="text" onChange={e => setAge(e.target.value)} />    </div>  );};export default MyAwesomeFuncComponent;
import React, { Component } from "react";import ReactDOM from "react-dom";class MyOldClassComponent extends Component {  constructor(props) {    super(props);    this.state = {      name: ''    };    this.setName = this.setName.bind(this);  }  setName(e) {    this.setState({      name: e.target.value    });  }  render() {    return (      <div>        <h1>Hello {this.state.name}</h1>        <input type="text" onChange={this.setName} />      </div>    );  }}export default MyOldClassComponent;

Effect hook

import React, { useEffect, useStqte } from "react";import ReactDOM from "react-dom";const MyAwesomeFuncComponent = props => {  // Aquí viene la magia  const [name, setName] = useState();  // "componentDidMount"  useEffect(() => {    fetch(API_URL)      .then(r => r.json())      .then(d => setName(d.name));    });  return (    <div>      {name && <h1>Here is your name: {name}</h1>}      {!name && <div>Loading...</div>}   </div>  );};export default MyAwesomeFuncComponent;

Conclusiones

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store