简体   繁体   中英

Logical understanding react hooks, difference between useState and useEffect (or state and lifecycle methods)

I can not get the concept of logical difference between useState and useEffect, to be more precisely, between state and lifecycle methods. For instance, I have watched tutorials, and see this example for useEffect:

const UseEffectBasics = () => {
  const [value, setVal] = useState(0);
  const add = () => {
    setVal((x) => { return x + 1 })
  }
   useEffect(() => {
    if (value > 0) {
      document.title = `Title: ${value}`
    }
   },[value])
  return <>
    <h1>{value}</h1>
    <button className="btn" onClick={add}>add</button>
  </>;
};

When we are clicking to button, title of the document shows us increasing numbers by one. I played little bit, and removed useEffect method at all, and did this instead:

const UseEffectBasics = () => {
  const [value, setVal] = useState(0);
  document.title = `Title: ${value}`
  const add = () => {
    setVal((x) => { return x + 1 })
  }
  return <>
    <h1>{value}</h1>
    <button className="btn" onClick={add}>add</button>
  </>;
};

And guess what, it worked same as the previous code. So, how useEffect actually works, what is the motivation of this method?

PS : Do not send me links of documentation, some basic tutorials, please, be sure, I have been researched. I know that I am missing very simple, very basic something but I do not know what is that, and where to focus to solve it.

Using useEffect to track stateful variable changes is more efficient - it avoids unnecessary calls by only executing the code in the callback when the value changes, rather than on every render.

In the case of document.title , it doesn't really matter, since that's an inexpensive operation. But if it was runExpensiveFunction , then this approach:

const UseEffectBasics = () => {
  const [value, setVal] = useState(0);
  runExpensiveOperation(value);

would be problematic, since the expensive operation would run every time the component re-renders. Putting the code inside a useEffect with a [value] dependency array ensures it only runs when needed - when the value changes.

This is especially important when API calls that result from state changes are involved, which is pretty common. You don't want to call the API every time the component re-renders - you only want to call it when you need to request new data, so putting the API call in a useEffect is a better approach than putting the API call in the main component function body.

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