React how to run a function only once, after page enter or refresh

Ste*_*ois 5 javascript reactjs react-hooks use-effect

I'm working on a search function with algolia search. The user may put in a search term from a different site, get redirected to the search page, and the search should be invoked.

After this, to search for more stuff, the user need to use the search bar in the search page, and hit enter to invoke the search again.

I've tried to use a useState and set it to true after the first render. However when I type in my search bar, the useEffect gets invoked at every key press. Why is this happening when firstRender doesn't change? It will set firstRender to true again, but since firstRender already is true, nothing should happen?

How can I "deactivate" the useEffect after the first render, so that the user only uses the search bar to search?

(I don't want to hammer the API with requests while the user is typing)

Thanks!

const SearchRecipes = () => {
  const client = algoliasearch(process.env.REACT_APP_ALGOLIA_APP_ID, process.env.REACT_APP_ALGOLIA_SEARCH_API);
  const index = client.initIndex('recipe_search');
  const match = useRouteMatch();
  const [searchTerm, setSearchTerm] = useState(match.params.id);
  const [searchReturnData, setSearchReturnData] = useState([]);
  const [firstRender, setFirstRender] = useState(false);
  const useMountEffect = (fun) => useEffect(fun, [])


  useEffect(() => {
    handleSubmit();
    setFirstRender(true);
  }, [firstRender])

  const handleSubmit = (e = null) => {
    if (e !== null){
      e.preventDefault();
    }

    index
      .search(searchTerm)
      .then((responses) => {
        setSearchReturnData(responses.hits);
      });
  }

  return (
    // irrelevant JSX
   <div className="keywords">
     <input 
       type="text" 
       value={searchTerm}
       onChange={({target}) => setSearchTerm(target.value)}
     />
   </div>
   // more irrelevant JSX
  )
} 
Run Code Online (Sandbox Code Playgroud)

Bru*_*iro 3

原因是您对其useEffect有依赖firstRender并且在其内部设置该值。

您可以按照评论中的建议,使用空的依赖项数组:

useEffect(() => {
  handleSubmit();
}, [])
Run Code Online (Sandbox Code Playgroud)

或检查您的firstRender状态是否已设置:

useEffect(() => {
  if (!firstRender) {
    handleSubmit();
    setFirstRender(true);
  }
}, [firstRender])
Run Code Online (Sandbox Code Playgroud)

如果您需要更多信息,这是一篇非常好的文章useEffect