Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading