Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react hooks props in useEffect

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>    ) } 
like image 905
Mumfordwiz Avatar asked Mar 31 '19 09:03

Mumfordwiz


People also ask

Can you use props in useEffect?

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.

Can I use hooks inside useEffect?

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.

How do you use props in React hooks?

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.

Can we render component in useEffect?

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.


1 Answers

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.

like image 113
Ana Liza Pandac Avatar answered Sep 29 '22 07:09

Ana Liza Pandac