DEV Community

Discussion on: Why doesn't useState has a dependency array?

Collapse
 
jcubic profile image
Jakub T. Jankiewicz

I think it's kind of odd example if you call useState in useEffect the component will be caled twice which is normal behavior. Components are not guarantee to be called only once. They can be called multiple times. The most performance issue came from double update the DOM, which will not happen in this case.

Can you show real use case why you would call setState in useEffect?

Collapse
 
swadhwa16 profile image
Sumit Wadhwa • Edited

How would you propose changing state of a hook based on the prop passed to it?
An example would a count-down timer with reset functionality. If we're passing some future time to this custom hook, then the hook needs to update its internal state as well.

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

You define state inside the hook and return setValue and value from the hook, just like useState does you don't pass state to hook.

const useTimer = () => {
   const [count, setCount] = useState(0);
   function increment() {
     setCount(count+1);
   }
   function decrement() {
     setCount(count-1);
   }
   return {count, increment, decrement};
};
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
swadhwa16 profile image
Sumit Wadhwa

yes I think you're right. a hook's state should not depend on its props. it should be private and it should expose functions that trigger hook's state change so that we have more control over hook's state. thanks.

Thread Thread
 
peerreynders profile image
peerreynders • Edited

In hooks props are often used for state initialization:

const useCounter = (initialCount = 0) => {
   const [count, setCount] = useState(initialCount);
   function increment() {
     setCount(count+1);
   }
   function decrement() {
     setCount(count-1);
   }
   return {count, increment, decrement};
};
Enter fullscreen mode Exit fullscreen mode