I am learning NextJs & React.
And I found an interesting behaviour of React.
- Whenever I click the “click me” button, it changes state which is
test
. - Then totally non-related code
someTest
is executed again. someTest
hasfetch
and whenevertest
changes,fetch
is called. (I find this weird.)- I feel potentially lots of waste might cause due to this behaviour. Imagine that
someTest
has many processes such as multiple fetches and loops. How can I prevent? (ex: whentest
is changed,someTest
should not be executed)
// page.tsx
'use client';
import { someTest, } from "@/hooks/myHook";
import { useState } from "react";
export default function MyPage() {
const notRelatedCode = someTest();
const [test, setTest] = useState(false);
console.log(1);
return <>
<div>
<button onClick={() => {setTest(!test)}}>click me</button>
</div>
</>
}
// myHook.tsx
export const someTest = () => {
fetch(...)
console.log(0);
}