1

I'm sure I have got the wrong understanding on this. I have the following component

const Comp = () => {
    const filter = 'a';

    useEffect(() => {
      console.log('executing effect');
      loadFriends();
    }, [filter]);


    return (
      <Div>
        {friendsFilter}
      </Div>
    );
  };

Now as per my understanding, since the dependency list on useEffect is filter react should not run the effect when the component gets rendered again ? However it seems to run it. Am I understanding something wrong here?

Molly
  • 1,887
  • 3
  • 17
  • 34
tmp dev
  • 8,043
  • 16
  • 53
  • 108

2 Answers2

0

If you only want it to run once, use an empty array for the dependency value instead of `[filter]'.

Ed Lucas
  • 5,955
  • 4
  • 30
  • 42
0

Well, I have tested your use-case but it doesn't call the useEffect block.

Here is the code which I've tested.

import React, { useEffect, useState } from "react";

const Comp = () => {
  const [count, setCount] = useState(0);
  const filter = "a";

  useEffect(() => {
    console.log("executing effect");
    //loadFriends();
  }, [filter]);

  return (
    <div>
      Div
      <button onClick={() => setCount(count + 1)}> Click me</button>
      Count: {count}
    </div>
  );
};

export default Comp;

Link to codesandbox Even changing the count the component re-rendered but doesn't call the useEffect block.

Most probably there's something happening in loadFriends() which is changing the value of the filter.

Read more about useEffect here

Pratap Sharma
  • 2,633
  • 2
  • 18
  • 32
  • Thanks for this, even if `loadFriends` is changing anything, since the `filter` is hard-coded shouldn't the useEffect run only once ? – tmp dev Feb 03 '20 at 21:14
  • Well if you could share the code inside `loadFriends` i can give you a better answer. As the code above works perfectly fine without `loadFriends`. – Pratap Sharma Feb 04 '20 at 04:19