4 ms·
Seconded. Plus, you start writing wrapper functions for standard Javascript APIs (e. G. window.setInterval) to force them into Reacts data model.
by mikojan 5y ago
Seconded. Plus, you start writing wrapper functions for standard Javascript APIs (e. G. window.setInterval) to force them into Reacts data model.
- jameshart 5y ago... which is a good idea anyway because you want your code to be testable.
- mikojan 5y ago...this makes no sense at all.
- mikojan 5y agoWhy would you be down voting this? Parent's statement is completely nonsensical. If you wanted to test a function irrespective of window.setInterval's implementation you would just PASS window.setInterval as a parameter to that function. You would NOT add a wrapper function for window.setInterval because it is completely useless.
- jameshart 5y agoThe function you’re talking about would be a react functional component. I don’t think passing window.setInterval in as a prop to a react component is a particularly common approach to achieving component testability - though by all means give it a try. I don’t think it’s ‘nonsensical’ though to suggest that it’s a fairly common practice in testing to not want your unit tests to actually set up recurring callbacks. Isolating an external side effect to make it testable, as well as to align its abstraction with the one that your framework uses is a common pattern anyway. I’m not sure why this angers you so much?
- erikpukinskis 5y agoWhy would you do that? What’s wrong with this? useEffect(() => { const interval = setInterval(myFunc, 1000) return () => clearInterval(myInterval) },[]) I think one of the keys to React is not to fear the boilerplate. If you find yourself typing the same code too often, there’s probably a higher level abstraction that you should find, way above the level of setInterval. I find coders often try to DRY up low level code to the detriment of actually dealing with their _application_ architecture. In general, you should use the tools as provided, boilerplate and all, and then focus your real brain energies on the specific domain problems that only your application needs. Creating thin wrappers on external tools to squeeze the last tiny bits of DRYness is not only usually a waste of time, but it makes your code unreadable. People know how setInterval and useEffect work. If I see useInterval I have to go read your code to know what’s happening. Especially if you made it configurable. And people _will_ tend to add configuration to these wrappers over time as needs change.
- lunfard00 5y agoin my experience is better to have customs hooks like useTimeout (react-use library is awesome) so is easier to test. Mocking hooks feels nice, mocking the browser API not so much...