The case: you encounter an error when trying to make a custom hook, in react, or it’s just not working.
When you are trying to use React custom hooks you are seeing the following error:
Uncaught TypeError: Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.
It’s very likely that the cause to that is that when you trying to the custom hook – you access it like use State with destructive array:
[var1, func1] = useMyCustomHook();
This generates this error since the custom hook isn’t iterable, this mean, isn’t array. useState is returning array, custom hook isn’t necessary retruning array
** In my local area it generates error, in Stackblitz it’s just not showing the value but the compiler does the compiling. I guess it’s because the Stackblitz area, or due to compiler different version, didn’t checked it deeply.
The solution is simple, and very logic. Just access the customHook in regular way.
const var1 = useMyCusom();
Example
Take a look at the below example.
I have a functional component that use custom hook, that returns -1 if the provided number is <10 and 1 if num>10.
*Actually custom hooks is for use share state-logic with some components, but I didn’t demonstrated it in this example.
function MyHook(props){
const [state1, setState1] = useState('initial state');
//This won't work because you trying to access array but you get only number
const [customVal, setCustomVal] = useCustomCounter(20);
//It's should generate the error :
// nonIterableRest.js:2 Uncaught TypeError: Invalid attempt to destructure //non-iterable instance.
//BUT at stackblitz it's just doesn't show it.
//This will make it work
// const customVal = useCustomCounter(20);
return(
<div>
<h2>I am a functional component that use hooks</h2>
<p>This is my prop - {props.prop1}</p>
<p>This is my state - {state1}</p>
<button onClick = {()=>setState1('state1 new value')}>
U can change the state</button>
<p>This is my custom hook value = {customVal}</p>
</div>
);
}
function useCustomCounter(num){
//U can insert here some react logic...
if (num === null){
return 'loading';
}
return num > 10 ? 1 : -1;
}
This won’t work – since the above problem – you can see this live example.
Change the destructive array syntax to regular –
instead of
const [num, setNum] = useCustomCounter(0);
to
const num = useCustomCounter(0);
and it will WORK.
Exercise – Check if you did understand –
Take the above unworking live example, and try to fix it and make it work.
***About The Author***
Hope this article was useful for you. Feel free to write reply for any feedback you want, share it, and do like.
Thanks for reading.
I am Izhar Mashkif, a full-stack WEB developer from Israel.
yimprogramming@gmail.com, Linkedin, 054-7477637 .
Working with people that know the value of quality work, and want to advance their project forward.
Image by Momentmal from Pixabay