I have a scenario where I am to fetch data on a button click and store it in a context variable. Please check the code below:
const [products, setProducts] = useState([]);
const handleButtonClick= useCallback(() => {
if (countryCode) {
async function getproducts() {
try {
const apiData = await fetch(URL);
const jsonData = await apiData.json();
setProducts(jsonData);
} catch (error) {
console.error(error);
}
}
getproducts();
}
}, [targetGroup,countryCode]);
I would use this callback function: handleButtonClick()
on the button onClick(). I'm still new to React and I'm sometimes confused with React hooks. Is this a correct approach or is there no need for a callback function at all, just a normal function would do?
You don't need
useCallback
for this function, you can write a normal function and use it like this:<button onClick={handleButtonClick}>Click me</button>