Accessing up-to-date state from within a callback

For your scenario (where you cannot keep creating new callbacks and passing them to your 3rd party library), you can use useRef to keep a mutable object with the current state. Like so: function Card(title) { const [count, setCount] = React.useState(0) const [callbackSetup, setCallbackSetup] = React.useState(false) const stateRef = useRef(); // make stateRef always have … 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

React hooks useCallback with parameters inside loop

The simple answer here is, you probably shouldn’t use useCallback here. The point of useCallback is to pass the same function instance to optimized components (e.g. PureComponent or React.memoized components) to avoid unnecessary rerenders. You’re not dealing with optimized components in this case (or most cases, I’d suspect) so there’s not really a reason to … Read more

React w/hooks: prevent re-rendering component with a function as prop

The current preferred route is useCallback, which is the same as your useMemo solution, but with additional possible optimizations in the future. Pass an empty array [] to make sure the function will always have the same reference for the lifetime of the component. Here, you also want to use the functional state update form, … Read more

React – Is useState ‘s setter function able to change?

The setter function won’t change during component life. From Hooks FAQ: (The identity of the setCount function is guaranteed to be stable so it’s safe to omit.) The setter function (setState) returned from useState changes on component re-mount, but either way, the callback will get a new instance. It’s a good practice to add state … Read more

React hooks: Why do several useState setters in an async function cause several rerenders?

In react 17, if code execution starts inside of react (eg, an onClick listener or a useEffect), then react can be sure that after you’ve done all your state-setting, execution will return to react and it can continue from there. So for these cases, it can let code execution continue, wait for the return, and … Read more

Can I call separate function in useEffect?

TL;DR use useCallback() First of all, using a function as a dependency is very dangerous. If that function causes a state change, then the subsequent re-render will invoke the function again (through useEffect)… and an infinite loop begins. One thing you can do, as many suggest here, is to create the function within the useEffect() … Read more