Mouse events causing "Too many re-renders" in my functional component

Viewed 215

I am trying to use a ternary that changes my "titleHover" state variable based on mouse hovering an element. Unfortunately my code is giving me the following message "Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."

Have been searching for solutions but to no avail, although I am sure there is a very simple correction that needs to be made.

 
function Tsection(props) {

  const [titleHover, settitleHover] = useState(false);

  function handledelete() {
    props.onDelete(props.id);
  }

  return (
    <li className="tsection">
      <div onMouseEnter={settitleHover(true)} onMouseLeave={settitleHover(false)} className="sectiontitle">
        {
          props.title > 0 ? 
          props.title :
          <span>Untitled Section {props.id}</span>
        }
        { titleHover ? <i class="far fa-edit"></i> : null }
      </div>
      <i onClick={handledelete} className="far fa-trash-alt deleteimg"></i>
    </li>
  );

}

export default Tsection;
1 Answers

Right now, you're invoking settitleHover immediately when the component is rendered. You need to pass a callback instead of invoking it:

<div onMouseEnter={() => settitleHover(true)} onMouseLeave={() => settitleHover(false)} className="sectiontitle">
Related