5 Ways to Convert React Class Components to Functional Components w/ React Hooks
Publikováno: 19.11.2018
In the latest alpha release of React, a new concept was introduced, it is called Hooks. Hooks were introduced to React to solve many problems as explained in the Celý článek
In the latest alpha release of React, a new concept was introduced, it is called Hooks. Hooks were introduced to React to solve many problems as explained in the introduction to Hooks session however, it primarily serves as an alternative for classes. With Hooks, we can create functional components that uses state and lifecycle methods.
Related Reading:
Hooks are relatively new, as matter of fact, it is still a feature proposal. However, it is available for use at the moment if you'd like to play with it and have a closer look at what it offers. Hooks are currently available in React v16.7.0-alpha.
It's important to note that there are no plans to ditch classes. React Hooks just give us another way to write React. And that's a good thing!
Given that Hooks are still new, many developers are yet to grasp its concepts or understand how to apply it in their existing React applications or even in creating new React apps. In this post, we'll demonstrate 5 simple way to convert React Class Components to Functional Components using React Hooks.
Class without state or lifecycle methods
Let's start off with a simple React class that has neither state nor lifecycle components. Lets use a class that simply alerts a name when a user clicks a button:
import React, { Component } from 'react';
class App extends Component {
alertName = () => {
alert('John Doe');
};
render() {
return (
<div>
<h3> This is a Class Component </h3>
<button onClick={this.alertName}> Alert </button>
</div>
);
}
}
export default App;
Here we have a usual React class, nothing new and nothing unusual. This class doesn't have state or any lifecycle method in it. It just alerts a name when a button is clicked. The functional equivalent of this class will look like this:
import React from 'react';
function App() {
const alertName = () => {
alert(' John Doe ');
};
return (
<div>
<h3> This is a Functional Component </h3>
<button onClick={alertName}> Alert </button>
</div>
);
};
export default App;
Like the class component we had earlier, there's nothing new or unusual here. We haven't even used Hooks or anything new as of yet. This is because we've only considered an example where we have no need for state or lifecycle. But let's change that now and look at situations where we have a class based component with state and see how to convert it to a functional component using Hooks.
Class with state
Let's consider a situation where we have a global name variable that we can update within the app from a text input field. In React, we handle cases like this by defining the name variable in a state
object and calling setState()
when we have a new value to update the name
variable with:
import React, { Component } from 'react';
class App extends Component {
state = {
name: ''
}
alertName = () => {
alert(this.state.name);
};
handleNameInput = e => {
this.setState({ name: e.target.value });
};
render() {
return (
<div>
<h3> This is a Class Component </h3>
<input
type="text"
onChange={this.handleNameInput}
value={this.state.name}
placeholder="Your name"
/>
<button onClick={this.alertName}> Alert </button>
</div>
);
}
}
export default App;
When a user types a name in the input field and click the Alert
button, it alerts the name we've defined in state. Once again this is a simple React concept, however, we can convert this entire class into a functional React component using Hooks like this:
import React, { useState } from 'react';
function App() {
const [name, setName] = useState('John Doe');
const alertName = () => {
alert(name);
};
const handleNameInput = e => {
setName(e.target.value);
};
return (
<div>
<h3> This is a Functional Component </h3>
<input
type="text"
onChange={handleNameInput}
value={name}
placeholder="Your name"
/>
<button onClick={alertName}> Alert </button>
</div>
);
};
export default App;
Here, we introduced the useState
Hook. It serves as a way of making use of state in React functional components. With theuseState()
Hook, we've been able to use state in this functional component. It uses a similar syntax with destructuring assignment for arrays. Consider this line :
const [name, setName] = useState("John Doe")
Here, name
is the equivalent of this.state
in a normal class components while setName
is the equivalent of this.setState
. The last thing to understand while using the useState()
Hook is that it takes an argument that serves as the initial value of the state. Simply put, the useState()
argument is the initial value of the state. In our case, we set it to "John Doe"
such that the initial state of the name in state is John Doe.
This is primarily how to convert a class based React component with state to a functional component using Hooks. There are a lot more other useful ways of doing this as we'll see in subsequent examples.
Class with multiple state properties
It is one thing to easily convert one state property with useState
however, the same approach doesn't quite apply when you have to deal with multiple state properties. Take for instance we had two or more input fields for userName, firstName and lastName
then we would have a class based component with three state properties like this:
import React, { Component } from 'react';
class App extends Component {
state = {
userName: '',
firstName: '',
lastName: ''
};
logName = () => {
// do whatever with the names ... let's just log them here
console.log(this.state.userName);
console.log(this.state.firstName);
console.log(this.state.lastName);
};
handleUserNameInput = e => {
this.setState({ userName: e.target.value });
};
handleFirstNameInput = e => {
this.setState({ firstName: e.target.value });
};
handleLastNameInput = e => {
this.setState({ lastName: e.target.value });
};
render() {
return (
<div>
<h3> This is a Class Component </h3>
<input
type="text"
onChange={this.handleUserNameInput}
value={this.state.userName}
placeholder="Your username"
/>
<input
type="text"
onChange={this.handleFirstNameInput}
value={this.state.firstName}
placeholder="Your firstname"
/>
<input
type="text"
onChange={this.handleLastNameInput}
value={this.state.lastName}
placeholder="Your lastname"
/>
<button className="btn btn-large right" onClick={this.logName}>
{' '}
Log Names{' '}
</button>
</div>
);
}
}
export default App;
To convert this class to a functional component with Hooks, we'll have to take a somewhat unconventional route. Using the useState()
Hook, the above example can be written as:
import React, { useState } from 'react';
function App() {
const [userName, setUsername] = useState('');
const [firstName, setFirstname] = useState('');
const [lastName, setLastname] = useState('');
const logName = () => {
// do whatever with the names... let's just log them here
console.log(userName);
console.log(firstName);
console.log(lastName);
};
const handleUserNameInput = e => {
setUsername(e.target.value);
};
const handleFirstNameInput = e => {
setFirstname(e.target.value);
};
const handleLastNameInput = e => {
setLastname(e.target.value);
};
return (
<div>
<h3> This is a functional Component </h3>
<input
type="text"
onChange={handleUserNameInput}
value={userName}
placeholder="username..."
/>
<input
type="text"
onChange={handleFirstNameInput}
value={firstName}
placeholder="firstname..."
/>
<input
type="text"
onChange={handleLastNameInput}
value={lastName}
placeholder="lastname..."
/>
<button className="btn btn-large right" onClick={logName}>
{' '}
Log Names{' '}
</button>
</div>
);
};
export default App;
This demonstrates how we can convert a class based component with multiple state properties to a functional component using the useState()
Hook.
Here's the Codesandbox for this example.
https://codesandbox.io/s/ypjynxx16x
Class with state and componentDidMount
Let's consider a class with only state
and componentDidMount
. To demonstrate such a class, let's create a scenario where we set an initial state for the three input fields and have them all update to a different set of values after 5 seconds.
To achieve this, we'll have to declare an initial state value for the input fields and implement a componentDidMount()
lifecycle method that will run after the initial render to update the state values.
import React, { Component, useEffect } from 'react';
class App extends Component {
state = {
// initial state
userName: 'JD',
firstName: 'John',
lastName: 'Doe'
}
componentDidMount() {
setInterval(() => {
this.setState({
// update state
userName: 'MJ',
firstName: 'Mary',
lastName: 'jane'
});
}, 5000);
}
logName = () => {
// do whatever with the names ... let's just log them here
console.log(this.state.userName);
console.log(this.state.firstName);
console.log(this.state.lastName);
};
handleUserNameInput = e => {
this.setState({ userName: e.target.value });
};
handleFirstNameInput = e => {
this.setState({ firstName: e.target.value });
};
handleLastNameInput = e => {
this.setState({ lastName: e.target.value });
};
render() {
return (
<div>
<h3> The text fields will update in 5 seconds </h3>
<input
type="text"
onChange={this.handleUserNameInput}
value={this.state.userName}
placeholder="Your username"
/>
<input
type="text"
onChange={this.handleFirstNameInput}
value={this.state.firstName}
placeholder="Your firstname"
/>
<input
type="text"
onChange={this.handleLastNameInput}
value={this.state.lastName}
placeholder="Your lastname"
/>
<button className="btn btn-large right" onClick={this.logName}>
{' '}
Log Names{' '}
</button>
</div>
);
}
}
export default App;
When the app runs, the input fields will have the intial values we've defined in the state object. These values will then update to the values we've define inside the componentDidMount()
method after 5 seconds. Now, let's convert this class to a functional component using the React useState
and useEffect
Hooks.
import React, { useState, useEffect } from 'react';
function App() {
const [userName, setUsername] = useState('JD');
const [firstName, setFirstname] = useState('John');
const [lastName, setLastname] = useState('Doe');
useEffect(() => {
setInterval(() => {
setUsername('MJ');
setFirstname('Mary');
setLastname('Jane');
}, 5000);
});
const logName = () => {
// do whatever with the names ...
console.log(this.state.userName);
console.log(this.state.firstName);
console.log(this.state.lastName);
};
const handleUserNameInput = e => {
setUsername({ userName: e.target.value });
};
const handleFirstNameInput = e => {
setFirstname({ firstName: e.target.value });
};
const handleLastNameInput = e => {
setLastname({ lastName: e.target.value });
};
return (
<div>
<h3> The text fields will update in 5 seconds </h3>
<input
type="text"
onChange={handleUserNameInput}
value={userName}
placeholder="Your username"
/>
<input
type="text"
onChange={handleFirstNameInput}
value={firstName}
placeholder="Your firstname"
/>
<input
type="text"
onChange={handleLastNameInput}
value={lastName}
placeholder="Your lastname"
/>
<button className="btn btn-large right" onClick={logName}>
{' '}
Log Names{' '}
</button>
</div>
);
};
export default App;
This component does exactly the same thing as the previous one. The only difference is that instead of using the conventional state
object and componentDidMount()
lifecycle method as we did in the class component, here, we used the useState
and useEffect
Hooks. Here's a Codesanbox for this example.
https://codesandbox.io/s/jzoz2n97my
Class with state, componentDidMount and componentDidUpdate
Next, let's look at a React class with state and two lifecycle methods. So far you may have noticed that we've mostly been working with the useState
Hook. In this example, let's pay more attention to the useEffect Hook.
To best demonstrate how this works, let's update our code to dynamically update the <h3>
header of the page. Currently the header says This is a Class Component. Now we'll define a componentDidMount()
method to update the header to say Welcome to React Hooks after 3 seconds:
import React, { Component } from 'react';
class App extends Component {
state = {
header: 'Welcome to React Hooks'
}
componentDidMount() {
const header = document.querySelectorAll('#header')[0];
setTimeout(() => {
header.innerHTML = this.state.header;
}, 3000);
}
logName = () => {
// do whatever with the names ...
};
// { ... }
render() {
return (
<div>
<h3 id="header"> This is a Class Component </h3>
<input
type="text"
onChange={this.handleUserNameInput}
value={this.state.userName}
placeholder="Your username"
/>
<input
type="text"
onChange={this.handleFirstNameInput}
value={this.state.firstName}
placeholder="Your firstname"
/>
<input
type="text"
onChange={this.handleLastNameInput}
value={this.state.lastName}
placeholder="Your lastname"
/>
<button className="btn btn-large right" onClick={this.logName}>
{' '}
Log Names{' '}
</button>
</div>
);
}
}
export default App;
At this point, when the app runs, it starts with the initial header This is a Class Component and changes to Welcome to React Hooks after 3 seconds. This is the classic componentDidMount()
behaviour since it runs after the render function is executed successfully.
What if we want to dynamically update the header from another input field such that while we type, the header gets updated with the new text. To do that, we'll need to also implement the componentDidUpdate()
lifecycle method like this:
import React, { Component } from 'react';
class App extends Component {
state = {
header: 'Welcome to React Hooks'
}
componentDidMount() {
const header = document.querySelectorAll('#header')[0];
setTimeout(() => {
header.innerHTML = this.state.header;
}, 3000);
}
componentDidUpdate() {
const node = document.querySelectorAll('#header')[0];
node.innerHTML = this.state.header;
}
logName = () => {
// do whatever with the names ... let's just log them here
console.log(this.state.username);
};
// { ... }
handleHeaderInput = e => {
this.setState({ header: e.target.value });
};
render() {
return (
<div>
<h3 id="header"> This is a Class Component </h3>
<input
type="text"
onChange={this.handleUserNameInput}
value={this.state.userName}
placeholder="Your username"
/>
<input
type="text"
onChange={this.handleFirstNameInput}
value={this.state.firstName}
placeholder="Your firstname"
/>
<input
type="text"
onChange={this.handleLastNameInput}
value={this.state.lastName}
placeholder="Your lastname"
/>
<button className="btn btn-large right" onClick={this.logName}>
{' '}
Log Names{' '}
</button>
<input
type="text"
onChange={this.handleHeaderInput}
value={this.state.header}
/>{' '}
</div>
);
}
}
export default App;
Here, we have state
, componentDidMount()
and componentDidUpdate()
. So far when you run the app, the header updates to Welcome to React Hooks after 3 seconds as we defined in componentDidMount()
. Then when you start typing in the header text input field, the <h3>
text will update with the input text as defined in the componentDidUpdate()
method.
Now lets convert this class to a functional component with the useEffect()
Hook.
import React, { useState, useEffect } from 'react';
function App() {
const [userName, setUsername] = useState('');
const [firstName, setFirstname] = useState('');
const [lastName, setLastname] = useState('');
const [header, setHeader] = useState('Welcome to React Hooks');
const logName = () => {
// do whatever with the names...
console.log(userName);
};
useEffect(() => {
const newheader = document.querySelectorAll('#header')[0];
setTimeout(() => {
newheader.innerHTML = header;
}, 3000);
});
const handleUserNameInput = e => {
setUsername(e.target.value);
};
const handleFirstNameInput = e => {
setFirstname(e.target.value);
};
const handleLastNameInput = e => {
setLastname(e.target.value);
};
const handleHeaderInput = e => {
setHeader(e.target.value);
};
return (
<div>
<h3 id="header"> This is a functional Component </h3>
<input
type="text"
onChange={handleUserNameInput}
value={userName}
placeholder="username..."
/>
<input
type="text"
onChange={handleFirstNameInput}
value={firstName}
placeholder="firstname..."
/>
<input
type="text"
onChange={handleLastNameInput}
value={lastName}
placeholder="lastname..."
/>
<button className="btn btn-large right" onClick={logName}>
{' '}
Log Names{' '}
</button>
<input type="text" onChange={handleHeaderInput} value={header} />
</div>
);
};
export default App;
We've achieved exactly the same functionailty using the useEffect()
Hook. It's even better or cleaner as some would say because here, we didn't have to write separate codes for componentDidMount()
and componentDidUpdate()
. With the useEffect()
Hook, we are able to achieve both functions. This is because by default, useEffect()
runs both after the initial render and after every subsequent update.
Check out this example on this CodeSandbox.
https://codesandbox.io/s/ork242q3y
Convert PureComponent to React memo
React PureComponent works in a similar manner to Component. The major difference between them is that React.Component
doesn’t implement the shouldComponentUpdate()
lifecycle method while React.PureComponent
implements it. If your application's render()
function renders the same result given the same props and state, you can use React.PureComponent
for a performance boost in some cases.
Related Reading: React 16.6: React.memo() for Functional Components Rendering Control
The same thing applies to React.memo()
. While the former refers to class based componentrs, React memo refers to functional components such that when your function component renders the same result given the same props, you can wrap it in a call to React.memo()
to enhance performance. Using PureComponent
and React.memo()
gives React applications a considerable increase in performance as it reduces the number of render operations in the app.
Here, we'll demonstrate how to convert a PureComponent class to a React memo component. To understand what exactly they both do, first, let's simulate a terrible situation where a component renders every 2 seconds wether or not there's a change in value or state. We can quickly create this scenario like this:
import React, { Component } from 'react';
function Unstable(props) {
// monitor how many times this component is rendered
console.log(' Rendered this component ');
return (
<div>
<p> {props.value}</p>
</div>
);
};
class App extends Component {
state = {
value: 1
};
componentDidMount() {
setInterval(() => {
this.setState(() => {
return { value: 1 };
});
}, 2000);
}
render() {
return (
<div>
<Unstable value={this.state.value} />
</div>
);
}
}
export default App;
When you run the app and check the logs, you'll notice that it renders the component every 2 seconds without any change in state or props. As terrible as it is, this is exactly the scenario we wanted to create so we can show you how to fix it with both PureComponent
and React.memo()
.
Most of the time, we only want to re-render a component when there's been a change in state or props. Now that we have experienced this awful situation, let's fix it with PureComponent
such that the component only re-renders when there's a change in state or props. We do this by importing PureComponent
and extending it like this:
import React, { PureComponent } from 'react';
function Unstable(props) {
console.log(' Rendered Unstable component ');
return (
<div>
<p> {props.value}</p>
</div>
);
};
class App extends PureComponent {
state = {
value: 1
};
componentDidMount() {
setInterval(() => {
this.setState(() => {
return { value: 1 };
});
}, 2000);
}
render() {
return (
<div>
<Unstable value={this.state.value} />
</div>
);
}
}
export default App;
Now if you run the app again, you only get the initial render. Nothing else happens after that, why's that ? well, instead of class App extends Component{}
now we have class App extends PureComponent{}
This solves our problem of re-rendering components, without respect to the current state. If however, we change this method:
componentDidMount() {
setInterval(() => {
this.setState(() => {
return { value: 1 };
});
}, 2000);
}
To:
componentDidMount() {
setInterval(() => {
this.setState(() => {
return { value: Math.random() };
});
}, 2000);
}
The component will re-render each time the value updates to the next random number. So, PureComponent
makes it possible to only re-render components when there's been a change in state or props. Now let's see how we can use React.memo()
to achieve the same fix. To do this with React memo, simply wrap the component with React.memo()
Like this:
import React, { Component } from "react";
const Unstable = React.memo(function Unstable (props) {
console.log(" Rendered Unstable component ");
return <div>{props.val} </div>;
});
class App extends Component {
state = {
val: 1
};
componentDidMount() {
setInterval(() => {
this.setState({ val: 1 });
}, 2000);
}
render() {
return (
<div>
<header className="App-header">
<Unstable val={this.state.val} />
</header>
</div>
);
}
}
export default App;
This achieves the same result as PureComponent
did. Hence, the component only renders after the initial render and doesn't re-render again until there's a change in state or props. Here's the Codesandbox for this example.
https://codesandbox.io/s/100zmv7ljj
Conclusion
In this post we have demonstrated a few ways to covert an existing class based component to a functional component using React Hooks. We have also looked at a special case of converting a React PureComponent
class to React.memo()
. It may be obvious but i still feel the need to mention that in order to use Hooks in your applications, you'll need to update your React to the supported version:
"react": "^16.7.0-alpha",
"react-dom": "^16.7.0-alpha",
React Hooks is still a feature proposal, however, we are hoping that it will be part of the next stable release as it makes it possible for us to eat our cake (use state in function components) and still have it back (retain the simplicity of writing functional components).