score:66
You can make use of useRef and store the props to be used within a closure such as render useEffect return callback method
function Home(props) {
const val = React.useRef();
React.useEffect(
() => {
val.current = props;
},
[props]
);
React.useEffect(() => {
return () => {
console.log(props, val.current);
};
}, []);
return <div>Home</div>;
}
However a better way is to pass on the second argument to useEffect
so that the cleanup and initialisation happens on any change of desired props
React.useEffect(() => {
return () => {
console.log(props.current);
};
}, [props.current]);
score:0
useEffect(() => {
if (elements) {
const cardNumberElement =
elements.getElement('cardNumber') || // check if we already created an element
elements.create('cardNumber', defaultInputStyles); // create if we did not
cardNumberElement.mount('#numberInput');
}
}, [elements]);
score:1
useLayoutEffect
is great for cleaning eventListeners on DOM nodes.
Otherwise, with regular useEffect
ref.current will be null on time hook triggered
More on react docs https://reactjs.org/docs/hooks-reference.html#uselayouteffect
import React, { useLayoutEffect, useRef } from 'react';
const audioRef = useRef(null);
useLayoutEffect(() => {
if (!audioRef.current) return;
const progressEvent = (e) => {
setProgress(audioRef.current.currentTime);
};
audioRef.current.addEventListener('timeupdate', progressEvent);
return () => {
try {
audioRef.current.removeEventListener('timeupdate', progressEvent);
} catch (e) {
console.warn('could not removeEventListener on timeupdate');
}
};
}, [audioRef.current]);
Attach ref to component DOM node
<audio ref={audioRef} />
score:12
useLayoutEffect() is your answer in 2021
useLayoutEffect(() => {
return () => {
// Your code here.
}
}, [])
This is equivalent to ComponentWillUnmount.
99% of the time you want to use useEffect, but if you want to perform any actions before unmounting the DOM then you can use the code I provided.
Source: stackoverflow.com
Related Query
- componentWillUnmount with React useEffect hook
- Uncaught TypeError: create is not a function using useEffect React Hook with AJAX request
- React hook useEffect() under the hood. Does an effect scheduled with useEffect block the main thread?
- setTimeout not clearing with React useEffect hook on mobile devices
- Access old state to compare with new state inside useEffect react hook with custom hooks usePrevious
- Replace of setState callback in react hook with useEffect hooks for complicated scenario not working
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- How to reset React hook state with setTimeout in useEffect
- How to check if state default boolean false is changing to true with React Hook useEffect
- React useEffect hook with long running task and merge state
- React setState hook not working with useEffect
- React useEffect hook with warning react-hooks/exhaustive-deps
- Using React useEffect hook with rxjs mergeMap operator
- Elements not displaying with .map() in react functional component with useEffect hook
- Refactor useEffect hook with useCallback - React
- Why does useEffect React Hook not work properly with dependency?
- React Hook UseEffect with className
- React Hook useEffect has a missing dependency with useEffect
- React Hook useEffect issue with setState
- React functional component useEffect hook with dependency equal in class component lifecycles
- React Hook useEffect has a missing dependency with Useeffect hook. Is it bad practice to ignore this warning?
- How to do a custom logic and redirect to another pages in react or nextjs with useEffect hook
- React useEffect hook is not working with rails
- React Hook not setting with useEffect
- Can't perform a React state update on an unmounted component with useEffect hook
- React Hook UseEffect in combination with Firebase creating infinite loop
- React useEffect hook with empty dependency render multiple times
- React hook using useEffect with an array inside the dependencies array
- NextJs: Calling setInterval with a variable for time inside of a React useEffect Hook
- React hook useEffect failed to read new useState value that is updated with firebase's firestore realtime data
More Query from same tag
- How in React check if two conditions are true
- React OnClick for item not working
- MERN: How to access build folder for Heroku deployment?
- How to refer to another class from a function in React JS?
- How do I call a function on button click to listen for another mouse click in React Hooks?
- Use hook in onClick
- ES6 Fat Arrow and Parentheses `(...) => ({...})`
- How to join after cornerRadius is provided for piecharts in recharts
- What does "Deprecated. Instead, use composability." mean in Reactjs Material-UI menuItems?
- amcharts Export with Meteor + React (JSX)
- Jest: `npm test` not displaying "Watch Usage" options in Windows Git Bash
- Unexpected empty object pattern no-empty-pattern
- how pass input props of redux form to custom select dropdown
- React 13.3 unmountComponentAtNode() Error: Target container is not a DOM element
- What's the proper way to work with 'react-leaflet' library in a react app made with 'create-react-app'?
- How to add key to React Component object
- React with redux-saga dispatch logout action on 401
- React MUI V5 AppBar Background color not changing
- how to compile typescript with react definitions
- React JS: Filtering an array of objects by another array of objects. How to sequential execute four functions incl. several API calls
- A Router may have only one child element
- Download a file using a GET call on ReactJS
- React combobox select with an image and discription
- Why is React-app state not re-rendering here? How to get state to update in time
- Strongly typing the react-redux connect with typescript
- React useEffect not behaving as expected
- How to get URL query string on Next.js static site generation?
- Showing Real Time Variable Value In <Text> Component - React Native
- Infer my object interface to type "object"
- in React, how to call a function living in another component?