score:3
the way i understood the question is that, you want to stop tracking the mouse movement.
if my understanding is correct, you can pass a flag to start/top tracking the mouse movement.
this demo shows that you can turn on/off the mouse tracking and
you can simply pass a variable, which you can check within your useeffect
.
function usemouseposition(shouldtrack = true) {
let [mouseposition, setmouseposition] = usestate({
x: null,
y: null
});
function handlemousemove(e) {
setmouseposition({
x: e.pagex,
y: e.pagey
});
}
useeffect(() => {
if (!shouldtrack) return;
window.addeventlistener("mousemove", handlemousemove);
return () => {
window.removeeventlistener("mousemove", handlemousemove);
};
}, [shouldtrack]);
return mouseposition;
}
function app() {
const [usemouse, setusemouse] = usestate(true);
let { x, y } = usemouseposition(usemouse);
useeffect(() => {
console.log(`x, y`, x, y);
}, [x, y]);
return (
<div classname="app">
<h1>hello codesandbox</h1>
<h2>start editing to see some magic happen!</h2>
<button onclick={() => setusemouse(_ => !_)}>
tracking mouse movement is {usemouse ? "on" : "off"}
</button>
</div>
);
}
clicking on the button toggles the track status.
and for "removing the hook", you can't as it's embedded in your function component. you can at least prevent the "side effect" from running using a condition.
⚠ note that useeffect
has a dependency as [shouldtrack]
.
score:0
you need to specify conditions in handlemousemove
in the next solution, you stop render outside the pink border and remove the listener under the black line.
note: added
usecallback
anddep array
because of unnecessary renderings.
const isinsidebox = ({ pagex, pagey }) =>
left <= pagex && pagex <= right && top <= pagey;
function usemouseposition() {
let [mouseposition, setmouseposition] = usestate({
x: null,
y: null
});
const handlemousemove = usecallback(
e => {
isinsidebox(e) && // add condition for border
setmouseposition({
x: e.pagex,
y: e.pagey
});
e.pagey >= bottom && // add condition for black line
window.removeeventlistener("mousemove", handlemousemove);
},
[setmouseposition]
);
useeffect(() => {
window.addeventlistener("mousemove", handlemousemove);
return () => {
window.removeeventlistener("mousemove", handlemousemove);
};
}, [handlemousemove]);
return mouseposition;
}
Source: stackoverflow.com
Related Query
- How to remove React hook in certain conditions?
- How to prevent race conditions with react useState hook
- How to change/add value of a certain row of an array using useState Hook in React
- React Hook useEffect has a missing dependency: 'setValid' . How to remove this warning
- How to remove navbar from certain pages in react
- How to remove a object from an array in react hook
- How do you remove a CSS class from a certain element of a list with React
- How to remove className in react after certain time
- How to fix missing dependency warning when using useEffect React Hook
- How to use callback with useState hook in react
- How to remove the default CRA react favicon?
- How to mock react custom hook returned value?
- How can I remove an attribute from a React component's state object
- How to use React useRef hook with typescript?
- How to make sure a React state using useState() hook has been updated?
- How to stop memory leak in useEffect hook react
- How to check how many React children have a certain prop?
- How can I remove unused imports/declarations from the entire project of React Typescript?
- How to remove query param with react hooks?
- How can remove console.log in the production build of a React application created using create-react-app?
- React hook form: How to can I use onChange on React Hook Form Version 7.0
- How To Solve The React Hook Closure Issue?
- React useReducer Hook fires twice / how to pass props to reducer?
- How to mock a custom hook inside of a React component you want to test?
- How to remove the new firebase onAuthStateChanged listener in react
- How to remove warning in React native
- how to update multiple state at once using react hook react.js
- Using React Router and Webpack 2 how to require external libraries only on certain routes?
- How to implement multiple checkbox using react hook
- React JS: how to properly remove an item from this.state.data where data is an array of objects
More Query from same tag
- API Call Not Returning Information
- Pass array to component
- How should I update individual items' className onClick in a list in a React functional component?
- react-google-maps calls empty InfoWindow
- React Hooks: toggle element on map function
- useState() is not updating state from event handler?
- How to correctly catch change/focusOut event on text input in React.js?
- react-native: borderRadius does not frame component right
- React-boilerplate: Implementing JWT authentication. Attempting to dispatch action from service
- How to use replace() in a useState string?
- React access one components function from another
- React componentsDidUpdate vs SetState callback
- React Javascript trouble with passing user input onchange to a parent component
- How to achieve an async function chain with await when the functions are parent and child?
- How can I compare values of sets in js
- Cross origin error thrown on GraphQL subscription
- How to properly declare a module for React and Require without Node?
- Objects are not valid as a React child - having to access to two children
- React doesn't re-render component with new props when state changes
- Read data from request which just finished
- Can I nest JSX Tags into one another using traditional JS syntax?
- Automatically adjust width of chip component (div) based on text of child elements
- React-Table: exception thrown calling 'getResolvedState()' on component ref
- React Hooks, how to share state between two functions
- Next.Js React app with styled components. Warning: Prop `className` did not match. Server: "x" Client: "y"
- Why does React-Magic-Move example break in JSFiddle with "Only a ReactOwner can have refs" error?
- Ant design sort table code not working on the react typescript
- Render function in reactjs
- How to construct an Array to first compare and then add the input
- eslint: Unexpected block statement surrounding arrow body