React is complaining about code below, saying it useEffect is being called conditionally:
I would argue there is a way to call hooks conditionally. You just have to export some members from that hook. Copy-paste this snippet in codesandbox:
import React from "react";
import ReactDOM from "react-dom";
function useFetch() {
return {
todos: () =>
fetch("https://jsonplaceholder.typicode.com/todos/1").then(response =>
response.json()
)
};
}
const App = () => {
const fetch = useFetch(); // get a reference to the hook
if ("called conditionally") {
fetch.todos().then(({title}) =>
console.log("it works: ", title)); // it works: delectus aut autem
}
return null;
};
const rootElement = document.getElementById("root");
ReactDOM.render( , rootElement);