我正在尝试使用useState
在函数内部运行带有useCallback
的变量的函数
仅当使用return
钩中的useEffect
卸载组件时,此功能才应运行:
import React, { useEffect, useCallback, useState } from "react";
import "./styles.css";
export default function App() {
const [search, setSearch] = useState("");
const update = useCallback(() => {
console.log({ search });
}, [search]);
useEffect(() => {
return () => {
update();
console.log("I ONLY WANT THIS TO RUN ON UNMOUNT");
};
}, [update]);
return (
<div className="App">
<input defaultValue={search} onChange={e => setSearch(e.target.value)} />
</div>
);
}
https://codesandbox.io/s/react-useeffect-btrbi?file=/src/App.js