I want to create a list of functionalities that I can access easily from anywhere on my app by simply importing the component. Here is what my component looks like:
functionalities.component.jsx
import { AES } from "crypto-js"
import { useContext, useState } from "react"
import { ConfigurationContext } from "../env"
const {configurationState} = useContext(ConfigurationContext);
const Functionalities = {
encrypt: (info) => AES.encrypt(info, configurationState.application.key).toString();
}
export default Functionalities
The problem I'm facing now is that I'm not able to use any context values since it would cause an error. Is there a way to implement "useContext" on this?
You can call a React Hook only inside a React component or inside a custom hook, it's one of the rules of the hooks.
The best you could do, if you need to share common functionalities, is creating a set of custom hooks.
import { AES } from "crypto-js"
import { useContext } from "react"
import { ConfigurationContext } from "../env"
const Functionalities = {
useEncrypt: () => {
const { configurationState } = useContext(ConfigurationContext);
return (info) => AES.encrypt(info, configurationState.application.key).toString();
}
};
export default Functionalities;
Example usage (always remember to call useContext inside a Context.Provider).
function EncryptComponent({info}) {
const encrypt = Functionalities.useEncrypt();
return <button onClick={() => encrypt(info)}>Encrypt</button>
}
I provide a CodeSandbox example that show how to do that.