So I have this method:
useEffect(() => {
//.. other logic here
// Firefox doesn't support looping video, so we emulate it this way
video.addEventListener(
"ended",
function() {
video.play();
},
false
);
}, [videoWidth, videoHeight]);
Now it throws an error where it says:
Assignments to the 'interval' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect.
I am confused on what does this mean? especially this part: To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '.current' property
.
To preserve the value over time, store it in a useRef Hook and keep the mutable value in the '. current' property. Otherwise, you can move this variable directly inside useEffect react-hooks/exhaustive-deps" This warning is displayed in the console and I don't know why. Also the handleLogin is not setting value.
In the useEffect , we are updating the useRef current value each time the inputValue is updated by entering text into the input field.
Placing useEffect inside the component lets us access the count state variable (or any props) right from the effect. We don't need a special API to read it — it's already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.
Storing element references with useRef To do this, create the ref, and then pass it into the element: const Component = () => { const ref = useRef(null); return <div ref={ref}> Hello world </div>; }; With this reference, you can do lots of useful things like: Grabbing an element's height and width.
The error is pointing you to the right direction. Use the useRef
hook to reference the video element. Since the handleVideo
function makes the dependencies of useEffect Hook change on every render we wrap the handleVideo
definition into its own useCallback()
Hook.
import React, { useEffect, useRef, useCallback } from "react";
function Video() {
const videoRef = useRef(null);
const handleVideo = useCallback(() => {
videoRef.current.play()
}, [])
useEffect(() => {
const video = videoRef.current
video.addEventListener('ended', handleVideo)
return () => {
video.removeEventListener('ended', handleVideo)
}
}, [handleVideo])
return <video width="400" controls ref={videoRef} src="https://www.w3schools.com/html/mov_bbb.mp4" />
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With