'Would this be considered "breaking the rules of hooks"?
I have a compound component that is used to build a bunch of different (but similar) screens in a react native app. Data comes from a CMS, and depending on the value of a prop called type
it needs to have different state variables, different validation, etc. I've written a config object who's methods map to the values of type
, and contain the state and functions needed for each use case. The pattern looks like this (edited for example sake):
import { useState } from 'react';
const MyComponent = props => {
const { type } = props; // possible values of type are 'A', 'B', 'C'
const config = {
A() {
const [value, setValue] = useState('');
function onChange({ target }) {
setValue(target.value);
}
return {
value,
onChange
}
},
B() {
// ...
return {
value: '',
onChange: () => {}
}
},
C() {
// ...
return {
value: '',
onChange: () => {}
}
}
}[type]();
return <input value={config.value} onChange={config.onChange} />
};
export default MyComponent;
BUT!
In the react docs it says this:
Don’t call Hooks inside loops, conditions, or nested functions.
My question is - does the above example violate the rules of hooks? It seems to work for what I need it to, but I suspect that it may cause problems. Would appreciate any thoughts / discussion. Cheers!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|