1

I have a basic custom hook in that I am changing a state inside useEffect but state is not changing

Below Users component is calling custom hook and passing items prop

const Users = (props) => {
  const [users] = usePivot(props.items)
}

usePivot custom hook

const usePivot = (propItems) => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    // this is printing in whenever propItems changes
    console.log("propItems in useUserPivot: ", propItems);
    
    // this is not setting
    setUsers(propItems);
  }, [propItems]);

  useEffect(() => {
    // this is not printing in console
    console.log("users: ", users);
  }, [users]);

  return [
    users
  ];

}

value of users is always [], it never changes.

  • You call `usePivot` in `User` component but your custom hook is called `useUserPivot`. If it's just a typo in your example then maybe it's because of `props.items` value always being an empty array? – Renaud Aubert Sep 28 '22 at 14:50
  • @RenaudAubert props.items is not empty, even useEffect is getting triggered when propItems is changing. – Chirag Panchal Sep 28 '22 at 15:12

2 Answers2

0

I used your same code here and everything is fine

enter image description here

make sure you are passing items as props to your users component based on your code

   <Users items={[1,2,3]} />
0

users state was getting set again in another function with sorted list, which is getting called in useEffect. I commented that function call and then issue got solved. I am not sure why this issue would come because of that.