React Hooks: useEffect() is called twice even if an empty array is used as an argument

Put the console.log inside the useEffect Probably you have other side effects that cause the component to rerender but the useEffect itself will only be called once. You can see this for sure with the following code. useEffect(()=>{ /* Query logic */ console.log(‘i fire once’); },[]); If the log “i fire once” is triggered more … Read more

How to use `setState` callback on react hooks

You need to use useEffect hook to achieve this. const [counter, setCounter] = useState(0); const doSomething = () => { setCounter(123); } useEffect(() => { console.log(‘Do something after counter has changed’, counter); }, [counter]); If you want the useEffect callback to be ignored during the first initial render, then modify the code accordingly: import React, … Read more

How to use componentWillMount() in React Hooks?

You cannot use any of the existing lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount etc.) in a hook. They can only be used in class components. And with Hooks you can only use in functional components. The line below comes from the React doc: If you’re familiar with React class lifecycle methods, you can think of useEffect … Read more

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

I suggest to look at Dan Abramov (one of the React core maintainers) answer here: I think you’re making it more complicated than it needs to be. function Example() { const [data, dataSet] = useState<any>(null) useEffect(() => { async function fetchMyAPI() { let response = await fetch(‘api/data’) response = await response.json() dataSet(response) } fetchMyAPI() }, … Read more

The useState set method is not reflecting a change immediately

Much like .setState() in class components created by extending React.Component or React.PureComponent, the state update using the updater provided by useState hook is also asynchronous, and will not be reflected immediately. Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their … Read more

How to fix missing dependency warning when using useEffect React Hook

If you aren’t using fetchBusinesses method anywhere apart from the effect, you could simply move it into the effect and avoid the warning useEffect(() => { const fetchBusinesses = () => { return fetch(“theURL”, {method: “GET”} ) .then(res => normalizeResponseErrors(res)) .then(res => { return res.json(); }) .then(rcvdBusinesses => { // some stuff }) .catch(err => … Read more

tech