How to rerender component in useEffect Hook

Think of your useEffect as a mix of componentDidMount, componentDidUpdate, and componentWillUnmount, as stated in the React documentation. To behave like componentDidMount, you would need to set your useEffect like this: useEffect(() => console.log(‘mounted’), []); The first argument is a callback that will be fired based on the second argument, which is an array of … Read more

How to setInterval for every 5 second render with React hook useEffect in React Native app?

You need to clear your interval, useEffect(() => { const intervalId = setInterval(() => { //assign interval to a variable to clear it. setState(state => ({ data: state.data, error: false, loading: true })) fetch(url) .then(data => data.json()) .then(obj => Object.keys(obj).map(key => { let newData = obj[key] newData.key = key return newData }) ) .then(newData => … Read more

Why shouldn’t I use catch() to handle errors in React useEffect API calls?

Everything I can find on this seems to link back to this github issue circa 2016. I’ll quote verbatim from there since it doesn’t appear to have been covered on Stack Overflow before and it explains things pretty thoroughly: .then(() => { this.setState({ loaded: true }) }) .catch(()=> { console.log(‘Swallowed!’) }); Your catch() handler is … Read more

Using document.querySelector in React? Should I use refs instead? How?

I can’t answer the “should you” part of whether to use refs for this instead other than if you do, you don’t need those id values unless you use them for something else. But here’s how you would: Use useRef(null) to create the ref. const activeSlideRef = useRef(null); Put it on the Slide that’s currently … Read more

Getting error after I put Async function in useEffect

You’re returning the result of calling getResponse() from the useEffect function. If you return anything from useEffect, it has to be a function. Changing your code to this should fix it because you’re no longer returning anything from the useEffect function. useEffect(() => { getResponse(); }); The useEffect Cleanup Function If you return anything from … Read more

What does it mean to ‘move this variable directly inside useEffect’ in this error message?

About useEffect hook: By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. more This means that function inside useEffect will be called after rendering of … Read more