Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  17] [ 4]  / answers: 1 / hits: 5619  / 4 Years ago, wed, june 10, 2020, 12:00:00

Can we dynamically import hooks based on the value passed to the component?



For eg.



App.js



<BaseComponent isActive />


BaseComponent.js



if(props.isActive) {
// import useActive (custom Hook)
}


I donot want these(custom hook) files to be imported and increase the size of BaseComponent even when the props contain falsey values.


More From » reactjs

 Answers
0

You can dynamically import hooks as it is just a function (using require), but you shouldn't because you can't use hooks inside conditions.



See Rules of Hooks




Only call Hooks at the top level. Don’t call Hooks inside loops, conditions, or nested functions.




If you want conditionally use a hook, use the condition in its implementation (look for example at skip option of useQuery hook from Apollo GraphQL Client).



const useActive = (isUsed) => {
if (isUsed) {
// logic
}
}

[#3530] Saturday, June 6, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;