How can I use custom method in useEffect?? If I create many components and they use same fetch function, Shoud I declare fetch function in every component's effect?? The function does same work??
As far as I know, If I want to use component's state in useEffect, I should declare and call that function in useEffect likes example 1.
But I want to declare the function other js file. Because it was called other components.
According to Dan Abramov (https://overreacted.io/a-complete-guide-to-useeffect/), If I want to move function, I must use useCallback method. But I didn't understand well. Please give me any advice this issue.
1. Component.js
const Component = () => {
const [id,setId] = useState(0);
const dispatch = useDispatch();
useEffect(() => {
fetch(`url/${id}`).then(res => dispatch({type: success, payload: res}))
},[id])
}
2. Component.js
const Component = () => {
const [id, setId] = useState(0);
useEffect(()=> {
callApi(id)
},[id])
}
Api.js
const callApi = (id) => {
const dispatch = useDispatch();
return fetch(`url/${id}`).then(res => dispatch({type:success, payload:res})
}
Shoud I declare fetch function in every component's effect?
Extract a custom hook, useFetch()
, with the same fetch functionality.
// custom hook
const useFetch = (id) => {
const [data, setData] = useState(null);
useEffect(
() => {
async function fetchData() {
const res = await fetch(`url/${id})
setData(res);
}
fetchData();
}, [id] // id as dependency
)
return data;
}
// sample component using custom hook
const Component = (props) => {
const dispatch = useDispatch();
const data = useFetch(props.id); // use custom hook
useEffect(
() => {
if (data) {
dispatch({type: success, payload: data});
}
}, [data] // dispatch every time data changes
)
}