When we’re creating React components with classes, we run our code that loads when the component mounts in the componentDidMount
hook.
However, with React components, this isn’t available.
In this article, we’ll look at how to produce the same result with the componentDidMount
hook within React function components.
The useEffect Hook
To run code only when the component mounts, we can use the useEffect
hook.
If we pass in an empty array as the 2nd argument, then the useEffect
callback in the 1st argument will only run when the component mounts.
For instance, we can write:
import React, { useEffect } from "react";
export default function App() {
useEffect(() => {
console.log("mounted");
}, []);
return <div className="App"></div>;
}
Now we should only see the 'mounted'
string logged when we mount the component.
React Hooks Equivalent of componentDidUpdate
The equivalent of the componentDidUpdate
lifecycle method is also the useEffect
hook.
componentDidUpdate
runs when a state or prop changes values.
We can do the same thing with useEffect
by passing in the state or prop values we want to watch into the array we pass into the 2nd argument of useEffect
.
For instance, we can write:
import React, { useEffect, useState } from "react";
const Count = ({ count }) => {
useEffect(() => {
console.log(count);
}, [count]);
return <p>{count}</p>;
};
export default function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<Count count={count} />
</div>
);
}
to watch the count
prop for updates with the useEffect
hook in the Count
component.
To watch a state, we can write:
import React, { useEffect, useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log(count);
}, [count]);
return (
<div className="App">
<button onClick={() => setCount((c) => c + 1)}>increment</button>
<p>{count}</p>
</div>
);
}
We watch the count
state the same way with the useEffect
hook.
React Hooks Equivalent of componentWillUnmount
The componentWillUnmount
lifecycle method in a React class component lets us run code when we unmount a component.
We can do the same thing with the useEffect
hook again.
We just have to return a function in the useEffect
callback to do this.
The function we return will run when the component unmounts.
For instance, we can write:
import React, { useEffect } from "react";
export default function App() {
useEffect(() => {
console.log("mounted");
return () => {
console.log("unmounted");
};
}, []);
return <div className="App"></div>;
}
to return a function in th useEffect
callback.
Then we should see 'unmounted'
when we unmount the App
component.
Conclusion
We can use the useEffect
hook in React function components to do the things that lifecycle methods can do in class components.