I have started using react-hooks
and there is something I am trying to understand. I have this useEffect
hook, I'm separating my useEffect
hooks, I want to know when each hook runs.
function MyComp(props) { useEffect( () => { fetchSomeData(props.filters) },[props.filters] ) return ( <div>will show my data here</div> ) }
Will this hook only run when props.filters
has changed?
Or do I have to use the prevProps
to check if it has changed?
Like this:
function MyComp(props) { const prevProps = useRef(props); useEffect( () => { if (prevProps.filters !== props.filters) { fetchSomeData(props.filters) } },[props.filters] ) return ( <div>will show my data here</div> ) }
useEffect() is for side-effects. A functional React component uses props and/or state to calculate the output. If the functional component makes calculations that don't target the output value, then these calculations are named side-effects.
You can't use a hook inside another hook because it breaks the rule Call Hooks from React function components and the function you pass to useEffect is a regular javascript function. What you can do is call a hook inside another custom hook.
In order to pass the isActive prop from the parent (MyCard) to the child (MyButton), we need to add MyButton as a child of MyCard. So let's import MyButton at the top of the file. import MyButton from "./Button"; Then, let's add MyButton as a child in the return statement of MyCard component.
Inside, useEffect compares the two objects, and since they have a different reference, it once again fetches the users and sets the new user object to the state. The state updates then triggers a re-render in the component.
If the value of props.filters
did not change, then React would skip the effect.
// This will only re-run if the value of `props.filters` changes useEffect(() => { fetchSomeData(props.filters); }, [props.filters]);
With hooks, React does this internally unlike the implementation using componentDidUpdate
where we have to compare the value of prevProps
and nextProps
against each other.
See optimizing performance by skipping effects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With