简体   繁体   中英

When I declare function in useEffect, it is not declared in html

I am implementing to change the state depending on it is hovered or not. But if I make it like the first code below, Too many re-renders. error will occur. In order to solve this problem, I used the useEffect to render only when the state changes, but an error called onHover is not defined occurs that the function declared in the user effect was not declared.

not using useEffect

import "./styles.css";
import { useState } from "react";

export default function App() {

  const [isHover, setIsHover] = useState(false);

  return (
    <button onMouseEnter={setIsHover(true)} onMouseLeave={setIsHover(false)}>
      click
    </button>
  );
}

using useEffect

import "./styles.css";
import { useEffect, useState } from "react";

export default function App() {

  const [isHover, setIsHover] = useState(false);

  useEffect(()=>{
    const onHover = () => {
      setIsHover(true)
    }
  },[isHover])

  return (
    <button onMouseEnter={onHover()} onMouseLeave={setIsHover(false)}>
      click
    </button>
  );
}

What should I do to use the function declared in useEffect?

As you just want to setState so no need to use useEffect. You can use without using useEffect as below.

import "./styles.css";
import { useState } from "react";

export default function App() {

  const [isHover, setIsHover] = useState(false);

  return (
    <button onMouseEnter={() => setIsHover(true)} onMouseLeave={() => setIsHover(false)}>
      click
    </button>
  );
}

It has to do with scope. The onHover function is defined within the useEffect hook, so it goes out of scope once you're out of the hook's block. You'll have to define it directly inside the component, outside of any other block scope, and simply call it inside useEffect .

It will still result in onHover called so many times until the mouse leaves the element in question. To prevent it, you could add a condition like so:

const onHover = () => {
  if (!isHover) {
    setIsHover(true);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM