In my React component, I want to trigger some action only when some state is changed. I initialized the state to be a default value and put it inside the dependency array of the hook. I am not changing this state at all during the session. However, React is still running the useEffect hook after the component is mounted for the first time.
I am wondering why it’s behaving like this. Is there a graceful way (or what would be the best practice) to achieve this? Thanks for the help!
The code is like this:
import React from 'react';
export function App(props) {
const [testString, setTestString] = React.useState('abc');
console.log(testString);
React.useEffect(() => {
console.log('******* I am not supposed to log here !!!')
}, [testString]);
return (
<div className='App'>
<h1>Hello React.</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Also available at playcode.io: https://playcode.io/1458690
2
Answers
Listen for when the component mounts (useEffect with empty dependency array) before the other useEffect (they are run in order) and set a flag there… How graceful it is, I don’t know, but it works:
According to the documentation for
useEffect
:You could use a ref to store whether or not the component has mounted to distinguish between the initial render and an update.
See also: Equivalent to componentDidUpdate using React hooks.