I have a class file, utility.js for all the common functions.
However some of the functions require certain library import
e.g: NetInfo library
utility.js
import NetInfo from "@react-native-community/netinfo";
export async function networkConnection() {
const state = await NetInfo.fetch();
return state.type;
}
However, in order for utility.js to be reusable in another project, another project has to have NetInfo installed. Is it a good practice if instead of importing modules directly, I import only when I need to use it, and pass the import object along to the function?
utility.js
export async function networkConnection({ NetInfo }) {
const state = await NetInfo.fetch();
return state.type;
}
and when using it
app.js
import NetInfo from "@react-native-community/netinfo";
import { networkConnection } from "./utility.js"
const network = networkConnection({ NetInfo })
This way, I can copy and paste utility.js to any project, without the need to install all the import packages. Also, this pattern seems to be able to resolve common Circular Dependencies error by limiting the import statement.
Is this the best practice for creating a common, reusable function file?
Your question illustrates the difference between a closure and a plain function, however, neither are pure.
If the function only serves to await a promise and return a property value, it doesn't really make sense to use the non-closure approach... unless you've created a module (utility.js in your example) with other exports unrelated to the NetInfo context. If that's the case, I think that's the issue to focus on: reorganization of your code's concerns.
How many characters it takes to get the value two ways:
console.log(`await networkConnection()`.length); // 25
console.log(`(await NetInfo.fetch()).type`.length); // 28
Is it worth the abstraction? Up to your brain and your fingers.