Refactoring a Class Component to a Functional Component, with Hooks

Class Component

import './App.css'; 
import React, {Component} from 'react';
import CardContainer from "./components/CardContainer";
class App extends Component {

state = {jokes: []}
componentDidMount = () => {
fetch('http://localhost:3000/jokes')
.then(response => response.json())
.then(jokes => this.setState({jokes}))
}
render() {
return (
<div className="content-container">
<CardContainer jokes={this.state.jokes} />
</div>
);
}
}
export default App;
  1. “class App extends Component{}” becomes “function App(){}”.
  2. You don’t need to wrap the return statement in a render function.
  3. You no longer need to use “this.” syntax, such as this.state or this.myFunction.
  4. useState replaces state = {} and this.setState().
  5. useEffect replaces componentDidMount, with one huge caveat: do not forget the dependency array!
  6. useEffect and useState must be imported, while you can drop the Component import.

Functional Component

import './App.css'; 
import React, { useState, useEffect } from 'react';
import CardContainer from "./components/CardContainer";
function App(){ const [jokes, setJokes] = useState({}) useEffect(() => {
fetch('http://localhost:3000/jokes')
.then(response => response.json())
.then(jokes => setJokes(jokes))
},[])
return (
<div className="content-container">
<CardContainer jokes={jokes} setJokes={setJokes}/>
</div>
);
}
export default App;
useEffect(() => {     
fetch('http://localhost:3000/jokes')
.then(response => response.json())
.then(jokes => setJokes(jokes))
},[])

--

--

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
Jeff Golden

Jeff Golden

24 Followers

Frontend developer, mountaineer, husband and dog wrangler.