Reputation: 167
I came across this when I was experimenting with react components. I have a component:
window.renderCount=1;
export function Soundscapes() {
const soundscape = useSelector((s) => s.tasks.soundscape);
const dispatch = useDispatch();
const [soundscapeAudioElement, setSoundscapeAudioElement] = useState(undefined);
useEffect(()=>{
console.log('state just changed to: ', soundscapeAudioElement )
},[soundscapeAudioElement])
console.log(window.renderCount);
window.renderCount=window.renderCount+1;
return (<SomeJSXUnrelatedToQuestion/>)
}
In the console, I noticed that the logs are 1,3,5,7,9
on subsequent re-rendering. I expected it to print renderCount
everytime it is incremented by 1 on the screen like 1,2,3,4,5
, each time the component got rendered to screen. But it seems to be incrementing it, but not printing it to console everytime.
Am I missing something here?
Upvotes: 3
Views: 2145
Reputation: 19843
You probably have StrictMode
on. StrictMode
will intentionally double invoke "render" and some other lifecycle methods to detect side-effects. Strict mode checks are run in development mode only; they do not impact the production build. Check the below snippet. Also, note that I have used React development CDNs.
function App() {
const [foo, setFoo] = React.useState(false)
const counter = React.useRef(0)
console.log(counter.current++)
return (
<button onClick={() => setFoo(f => !f)} > Click </button>
)
}
ReactDOM.render(<React.StrictMode><App /></React.StrictMode>, document.getElementById('mydiv'))
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<body>
<div id="mydiv"></div>
</body>
Upvotes: 11