As a react beginner, I’ve recently started trying to use hooks that really get stuck using the useEffect API

Pit treading Scenario 1: Event binding

UseEffect is initialized to listen for DOM scroll events. Scroll to the bottom of the page plus 1, perform the query method

So there’s a way

 const getData = () = > {
   console.log(page);
 };
 useEffect(() = > {
   const scrollDom = document.querySelector(".scroll-box");
   const func = () = > {
     setPage((page) = > page + 1);
     getData();
   };
   scrollDom.addEventListener("scroll", func);
   return () = > {
     scrollDom.removeEventListener("scroll", func); }; } []);Copy the code

If you write it this way, and you print all the initial values you’ll see that the useEffect dependency tells you that you need to wrap a getData method with a useCallback

So our code is going to be

const [page, setPage] = useState(0);
const getData = useCallback(() = > {
  console.log(page);
},[page]);

useEffect(() = > {
  const scrollDom = document.querySelector(".scroll-box");
  const func = () = > {
    setPage((page) = > page + 1);
    getData();
  };
  scrollDom.addEventListener("scroll", func);
  return () = > {
    scrollDom.removeEventListener("scroll", func);
  };
}, [getData]);
Copy the code

When the page changes, the getData will also change, and the useEffect will be executed again. Since then, the scroll event has been bound, right?

Let’s print the data to verify

 useEffect(() = > {
  console.log("Registration Method");
  const scrollDom = document.querySelector(".scroll-box");
  const func = () = > {
    setPage((page) = > page + 1);
    getData();
  };
  scrollDom.addEventListener("scroll", func);
  return () = > {
    console.log("Removal method");
    scrollDom.removeEventListener("scroll", func);
  };
}, [getData]);
Copy the code

Conclusion: useEffect destroys the corresponding method when a dependency changes and then updates the variables in the method

Scenario 2: Listen for route parameters

We often need to get the route ID and the corresponding data during page initialization

So the way we started is this

  useEffect(() = > {
    console.log("Request data 2", getQueryString("id")); } []);Copy the code

So at first glance it doesn’t seem to be a problem that if we change the id of the route, the page doesn’t change, right

The reason why console is not performed in the callback function at this time is because useEffect does not have dependencies

You need to write the parameters outside of the function

const id = getQueryString("id");
useEffect(() = > {
  console.log("Request data", id);
}, [id]);
Copy the code

This will render again

Conclusion: when we change the path parameters, the declarations in those functions will run again, and useEffect will decide whether to execute based on the dependencies