Languages
[Edit]
EN

React - is component removed hook

9 points
Created by:
FryerTuck
319

In this short article, we would like to show how to create React hook that stores information about component is removed or not yet.

Quick solution:

const useRemovedRef = (callback, dependences) => {
	const removedRef = useRef(false);
    useEffect(() => {
      	return () => {
        	removedRef.current = true;
        };
    }, []);
  	return removedRef;
};

// Usage example:

const removedRef  = useRemovedRef();

// removedRef.current   // true/false

Note: the main advantage of the solution is the possibility to access the current state in different places with React reference (by accessing removedRef.current).

 

Practical example

In this section we present an example where the programmer is able to check if the component is not removed after some async operation - it let to decide if we can set a new state for some hook inside the component.

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const useRemovedRef = (callback, dependences) => {
	const removedRef = React.useRef(false);
    React.useEffect(() => {
      	return () => {
        	removedRef.current = true;
        };
    }, []);
  	return removedRef;
};

// Usage example:

const App = () => {
    const removedRef = useRemovedRef();
  	const handleClick = () => {
        // it is place to put AJAX / Fetch request to server
        // next line simulates response recived from server after 1 second
    	setTimeout(() => {
          	// if removedRef.current stores false, we know the component is not removed yet and we can bind data
        	console.log(`Component removed: ${removedRef.current ? 'Yes' : 'No'}`);
        }, 1000);
    };
    return (
        <button onClick={handleClick}>Request backend</button>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

See also

  1. React - is component mounted hook
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join