javascriptreactjsreact-hooksrerender

App rerendering without the use of useEffect Hook


I am learning useEffect Hook in React and I have a question based on its usage.

Following is the code, which is still working fine as expected without the use of useEffect Hook.

My question is - if this code is working is it advisable to go ahead without adding useEffect in code or I am missing some concept here. I know there are other lifecycle methods that can be mimic in functional component using useEffect hook, but for small cases like this is it advisable to take this approach ?

Code -

import { useState } from 'react';

export default function App() {
  const [title, setTitle] = useState(null);
  const [num, setNum] = useState(2);
  // useEffect(() => {
  fetch(`https://jsonplaceholder.typicode.com/todos/${num}`)
    .then((response) => response.json())
    .then((response) => {
      const { title } = response;
      setTitle(title);
    });
  // }, []);

  return (
    <div className="App">
      <h1>useEffect Example</h1>
      <pre>{title}</pre>

      <button onClick={() => setNum(num + 1)}>Increment</button>
    </div>
  );
}

Solution

  • It would be extremely advisable to use useEffect here. If your App component re-renders for any reason, then your fetch logic will execute again.

    When you use useEffect with a dependency array, you ensure that the effect within useEffect is only executed when that dependency changes.

     useEffect(() => {
      fetch(`https://jsonplaceholder.typicode.com/todos/${num}`)
        .then((response) => response.json())
        .then((response) => {
          const { title } = response;
          setTitle(title);
        });
       }, [num]);