javascriptreactjsreact-hooks

useEffect is not executed when changing variable in custom hook


I am trying to create a custom hook which contains a state variable and a function to add a string to the given state variable:

  const [hiddenStatistics, setHiddenStatistics] = useState<String[]>(["a", "b"]);

  const moveTohiddenStatistics = (item: String) => {
    setHiddenStatistics((prevMovedItems) => [...prevMovedItems, item]);
  };

  return {
    hiddenStatistics,
    moveTohiddenStatistics,
  };

I am using this hook useHiddenStatistics in two other files. The first one (X) imports the array, the second file imports the moveTohiddenStatistics function in a similar way.

When executing the moveTohiddenStatistics, I can clearly see that an element is added to the array (It is rendered on the UI). But when adding a useEffect function in the first file (X) with the dependency of the hiddenStatistics, it does not fire. I am wondering why this is the case. I would like to execute some logic everytime the hiddenStatistics array has been changed. Whats going wrong?

File X:

const { hiddenStatistics } = useHiddenStatistics();

useEffect(() => {
    console.log("set hidden statistics");
}, [hiddenStatistics]);

Solution

  • From the docs:

    Custom Hooks let you share stateful logic, not state itself

    https://react.dev/learn/reusing-logic-with-custom-hooks#custom-hooks-let-you-share-stateful-logic-not-state-itself