When I use a react functional component with some state manager (I'm using recoil.js) and I try to update the state with a react hook it only calls useEffect when the state is different than the original state. When I was looming on stack overflow on how components rerender, they were talking about class components, and how they render every time setState is called. Is this just a difference between how the two components type work or am I just misunderstanding it?
This was my code test for function components:
import React, {useEffect} from 'react'
import ReactDOM from 'react-dom'
import {atom, useRecoilState, RecoilRoot} from 'recoil'
ReactDOM.render(
<React.StrictMode>
<RecoilRoot>
<App />
</RecoilRoot>
</React.StrictMode>,
document.getElementById('root')
);
const testAtom = atom({
key: "test",
default: ""
});
function App(){
return (
<>
<C1 />
<C2 />
</>
);
}
function C1(){
const [test, setTest] = useRecoilState(testAtom);
useEffect(() => {
console.log('effected', 'c1');
});
return (
<div>
<button onClick={() => {setTest('c1')}}>Click me</button>
</div>
);
}
function C2(){
const [test, setTest] = useRecoilState(testAtom);
useEffect(() => {
console.log('effected', 'c2');
});
return (
<div>
<button onClick={() => {setTest('c2')}}>Click me</button>
</div>
);
}
Running this useEffect is only called when the state is changed, not just when setTest is called, but this person said otherwise for class components.
React doesn't compare state data. When setState is called, it marks the component as dirty (which means it needs to be re-rendered).
Does this mean if I were to make this a class component that it would conoslelog every time?