- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - componentWillUnmount() Method
Components are the building blocks of our React app. They are similar to LEGO pieces that we assemble to make a larger building. componentWillUnmount() is one of the lifecycle methods available to each component.
The componentWillUnmount method is a part of the React class component. React calls it just before a component is removed or "unmounted" from the screen. This is a common location for cleaning up tasks such as canceling data fetching or deactivating subscriptions.
Syntax
componentWillUnmount() { // Cleanup and resource release logic here }
Parameters
componentWillUnmount does not accept any parameters. It is a lifecycle function that React calls when the component is going to be unmounted.
Return Value
Nothing should be returned by the componentWillUnmount function. It is used to do cleanup operations and release resources rather than return a value.
Examples
Example
Let us make a basic example app to show how the componentWillUnmount function in a React class component can be used. In this example, we will create a counter app that starts a timer when the component is mounted and stops it when it's unmounted.
import React, { Component } from 'react'; class App extends Component { state = { count: 0, }; timerID = null; componentDidMount() { // Start the timer when the component mounts this.timerID = setInterval(() => { this.setState((prevState) => ({ count: prevState.count + 1 })); }, 1000); } componentWillUnmount() { // Stop the timer when the component unmounts clearInterval(this.timerID); } render() { return ( <div> <h1>Counter: {this.state.count}</h1> </div> ); } } export default App;
Output
We have created a CounterApp component that extends Component. In the componentDidMount method, we started a timer with the help of setInterval to update the count state every second. This is a simple counter that increments every second. In the componentWillUnmount method, we stop the timer with the help of clearInterval to prevent memory leaks when the component is unmounted. The render method displays the current count value.
This app shows how to use the componentWillUnmount function to clear up resources. In our case it is to stop a timer, when a component is unmounted.
Example − User Profile App
In this app we will have a user profile display, and the componentWillUnmount() function is used for any cleanup that might be needed when the component is unmounted.
UserProfileApp.js
import React, { Component } from 'react'; import './App.css'; class UserProfileApp extends Component { state = { userProfile: { username: 'Akshay_Sharma', email: 'akshay@example.com', }, }; componentDidMount() { // Fetch user profile data when the component mounts } componentWillUnmount() { // Any cleanup needed for user profile app can be done here console.log('UserProfileApp will unmount'); } render() { const { username, email } = this.state.userProfile; return ( <div className='App user-profile-container'> <h1>User Profile</h1> <p>Username: {username}</p> <p>Email: {email}</p> </div> ); } } export default UserProfileApp;
App.css
.user-profile-container { max-width: 400px; margin: auto; padding: 20px; border: 1px solid #ccc; border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); background-color:rgb(224, 204, 178); } h1 { color: red; } p { margin: 8px 0; color: green; }
Output
Example − Countdown Timer App
In this app we will have a countdown timer that starts when the component mounts and stops when the component is about to unmount. So the code for this app is as follows −
CountdownTimerApp.js
import React, { Component } from 'react'; import './App.css' class CountdownTimerApp extends Component { state = { time: 10, }; timerID = null; componentDidMount() { // Start the countdown timer when the component mounts this.timerID = setInterval(() => { this.setState((prevState) => ({ time: prevState.time - 1 })); }, 1000); } componentWillUnmount() { // Stop the countdown timer when the component unmounts clearInterval(this.timerID); } render() { return ( <div className='App'> <h1>Countdown Timer: {this.state.time}s</h1> </div> ); } } export default CountdownTimerApp;
Output
The componentWillUnmount() method is used to clear intervals or perform cleanup when the components are about to unmount.
Limitations
During development in React's Strict Mode, React can use componentDidMount, immediately call componentWillUnmount, and then call componentDidMount again. This is a useful tool for identifying issues with componentWillUnmount and ensuring that it properly copies componentDidMount.
Summary
componentWillUnmount is a method in React class components that is used to clean up resources before clearing a component from the screen. It is required for operations such as stopping data fetching and deactivating subscriptions. We ensure that our component runs smoothly throughout its lifecycle by duplicating the behavior from componentDidMount.
To Continue Learning Please Login
Login with Google