I have created a custom hook to toggle between items from an array. This is the custom hook and how we use it in a component.
const { useState } = React;
function useToggleItems (arr){
const [count,setCount] = useState(0);
const [item , setItem] = useState(arr[count]);
function toggle(){
if(count<arr.length-1)
{
setCount(prev=>prev+1);
}
else
{
setCount(0);
}
setItem(arr[count]);
}
console.log(count);
return [item, toggle];
}
function App() {
const [item , toggle] = useToggleItems([1,2]);
return (
<div className="App">
<h1>{item}</h1>
<button onClick={toggle}>Button</button>
</div>
);
}
ReactDOM.createRoot(document.querySelector("#root")).render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I have tried to make this work but i don't know why it is forming a stale closure on first click and DOM is not getting updated with current value of count from useState. But after the first click it starts to work fine. Can some one help me fix this stale closure issue.
const [item,toggle] = useToggleItems(['a','b','c']);