$utils()
$utils()
is an accessor to reuse some utilities in multiple places in your application. It is a customizable utility to access function utilities to be used by different parts of an app.
Note: $utils() is only useful when you are using esModules. You don't need it in a script
tag (functions are accessible by default).
Even in esModules, you only need it if you don't want to pass functions as props.
Setup $utils() utility
Create stateAndUtilSetup.js
If you scaffold your application with create-render-app
, $utils()
comes with it in stateAndUtilSetup.js
file (In utilities folder). If you're using a script
tag, you need to create stateAndUtilSetup.js
file in your project and add the code from stateAndUtilSetup.js (opens in a new tab) to it.
Create utilities with setUtils
.
Create utilities for your entire app in a file and you can access them with $utils()
anywhere in the project.
import {setUtils} from './stateAndUtilSetup'
import {utils} from './appUtils'
const App = () => {
setUtils(utils);
//rest of the code
}
Now, you can use $utils()
anywhere in your project to reuse utilities.
Use $utils()
$utils()
takes no argument and it returns an object containing utility functions. It is immutable and can be used in various way.
- Get all utilities
const utils = $utils()
utils
now contains all the utilities you setup.
- Get an utility
const toggle = $utils().toggle
const show = $utils().show
$utils().toggle();
Reset or update $utils()
Since you create your utilities, you have to reset them manually. You can always remove unuse utility functions by hand.
Note: 80% of time, you don't need the $utils()
accessor. Instead, pass data, including function utilities, as props. When some utils
are needed by almost all parts of application, then you can use $utils()
.
Click to check the common errors in using $utils()
.