React useState rerender trigger behaves different depending of when its called - reactjs

Assuming you have a hook that has multiple useState, for example:
function useMyHook() {
const [s1, setS1] = useState();
const [s2, setS2] = useState();
const setFn = useCallback(
() => {
console.log('set s1');
setS1(Date.now());
console.log('set s2');
setS2(Date.now());
},
[setS1, setS2]
);
return setFn;
}
Now, depending of WHEN you call the setFn react will trigger either one or two rerender.
One rerender:
function MyComponent() {
console.log('render')
const setTwoStates = useMyHook()
// sync call => triggers only one re render
useEffect(() => setTwoStates(), [])
// console.logs are: render, set s1, set s2, render
return (
<div>hello</div>
);
}
Two rerenders:
function MyComponent() {
console.log('render')
const setTwoStates = useMyHook()
// as soon as the setFn is called in a later tick, react triggers two re renders
useEffect(() => setTimeout(setTwoStates, 1), [])
// console.logs are: render, set s1, render, set s2, render
return (
<div>hello</div>
);
}
Does anyone have an explanation for this? This can lead to unexpected behaviour depending how you call a hook.
I also created a small example repository in case you want to play around with this
https://github.com/JohannesMerz/react-setstate-rerenders

React will batch state setters when they set state in useEffect callbacks or event handlers (while the function is running) but in your async example the state is set after the effect function has returned.
const syncFn = () =>
console.log('in sync function');
const asyncFn = () => setTimeout(
()=>console.log('in async function'),
10
);
syncFn();
console.log('sync function returned');
asyncFn();
console.log('async function returned');
You can see in that snippet that in async function logs after async function returned so any set states that would happen would happen after the effect callback or event handler returned and cannot be batched unless you explicitly tell React to batch it.
You can use unstable_batchedUpdates to tell react to batch the updates:
const App = () => {
const [item1, setItem1] = React.useState(0);
const [item2, setItem2] = React.useState(0);
const render = React.useRef(0);
//mutate render ref (shows how often component is rendered)
render.current++;
const asyncUpdates = React.useCallback(() => {
Promise.resolve().then(() => {
ReactDOM.unstable_batchedUpdates(() => {
setItem1((item) => item + 1);
setItem2((item) => item + 1);
});
});
}, []);
const syncUpdates = React.useCallback(() => {
setItem1((item) => item + 1);
setItem2((item) => item + 1);
}, []);
const asyncNonBatchedUpdates = React.useCallback(() => {
Promise.resolve().then(() => {
setItem1((item) => item + 1);
setItem2((item) => item + 1);
});
}, []);
//using asyncUpdates in effect on mount
React.useEffect(asyncUpdates, []);
return (
<div>
<h1>Rendered: {render.current}</h1>
<div>
<div>item1:{item1}</div>
<div>item2:{item2}</div>
</div>
{/* run async updates as event handler */}
<button onClick={asyncUpdates}>async updates</button>
<button onClick={syncUpdates}>sync updates</button>
<button onClick={asyncNonBatchedUpdates}>
async non bathed updates
</button>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Related

Why is clearInterval not stopping my timer?

I am trying to build a timer with three buttons, a start, stop, where it stops on the current integer, and a reset. I have added my code below which results in the following issues.
I thought my stop function would stop the timer from decrementing but it continues to do so. Also, when logging my timer state in the console, you can see it does not update in the console even though it is updating in the DOM. Why is this?
Thank you for any insight at all.
import React from 'react';
import './style.css';
export default function App() {
const [timer, setTimer] = React.useState(50);
const reset = () => {
setTimer(50);
};
const start = () => {
setTimer((prev) => prev - 1);
};
// const interval = setInterval(() => {
// console.log(updated)
// //start() }, 1000)
// }
const interval = () => {
setInterval(() => {
console.log('updated');
console.log(timer);
start();
}, 1000);
};
const stop = () => {
clearInterval(start);
};
return (
<div>
<h1>{timer}</h1>
<button onClick={interval}>start</button>
<button onClick={stop}>stop</button>
<button onClick={reset}>reset</button>
</div>
);
}`
You have a small problem with assigning the actual value for the interval.
Here is how it should be in usage
const interval = setInterval(() => {})
clearInterval(interval)
For your code change, you can create a ref to keep the interval variable and use it to clean up the interval later.
function App() {
const [timer, setTimer] = React.useState(5);
const intervalRef = React.useRef(); //create a ref for interval
const reset = () => {
setTimer(5);
};
const start = () => {
setTimer((prev) => {
if(prev === 0) {
stop();
return 0;
}
return prev - 1;
});
};
// const interval = setInterval(() => {
// console.log(updated)
// //start() }, 1000)
// }
const interval = () => {
//assign interval ref here
intervalRef.current = setInterval(() => {
start();
}, 1000);
};
const stop = () => {
//clear the interval ref
clearInterval(intervalRef.current);
};
return (
<div>
<h1>{timer}</h1>
<button onClick={interval}>start</button>
<button onClick={stop}>stop</button>
<button onClick={reset}>reset</button>
</div>
);
}
ReactDOM.render(
<App/>,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
clearTimeout or clearInterval each take a token, which was returned by a previous call to setTimeout or setInterval. So you'll need to store that token:
const id = setInterval(() => console.log("triggered"), 1000);
// ...
clearInterval(id)
Also, you should be careful about what happens if App is re-rendered, so you should probably put the set/clear logic inside useEffect so you can cleanup your interval.
Also also, although you didn't ask, your console.log(timer) isn't going to work, and will always print 50. The timer variable inside that callback is captured once, and is never updated because that callback is just inside the setInterval now. You'll need to clear and reset your interval with an updated callback function every time App re-renders, or use a ref that you keep updated, which is a pain.
I would recommend borrowing this custom hook that considers all of these things for you: https://usehooks-ts.com/react-hook/use-interval
Then your App component could become extremely simple, but still be robust:
const { useEffect, useRef, useState, useLayoutEffect } = React;
// https://usehooks-ts.com/react-hook/use-interval
function useInterval(callback: () => void, delay: number | null) {
const savedCallback = useRef(callback);
useLayoutEffect(() => {
savedCallback.current = callback;
}, [callback])
useEffect(() => {
if (!delay && delay !== 0) return;
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
function App() {
const [timer, setTimer] = useState(50);
const [running, setRunning] = useState(false);
useInterval(() => setTimer(t => t - 1), running ? 1000 : null);
const start = () => setRunning(true);
const stop = () => setRunning(false);
const reset = () => { setTimer(50); };
return (
<div>
<h1>{timer}</h1><button onClick={start}>start</button>
<button onClick={stop}> stop </button>
<button onClick={reset}> reset </button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("react"));
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
I think you should not wrap your setTimeout into a callable. Then you lose the ability to start and stop it because the variable does not reference the interval but the callable that wraps the interval.
Take a look at this guide: https://www.w3schools.com/jsref/met_win_clearinterval.asp

React Suspense is not working as intended

I want to render fallback component when my Powers is being fetched/undefined. I implemented React.Suspense in my logic using the code:
<Suspense fallback={<p>Loading</p>}>
<RoutesPowers />
</Suspense>
and my RoutesPowers is
const Powers = [ ... ];
const RoutesPowers = () => {
const [powers, setPowers] = useState(null);
const fetchPowers = () => setTimeout(() => setPowers(Powers), 3000);
useEffect(() => fetchPowers(), []);
return ( powers.map(route => <RoutePowers route={route}/> )
};
but it gives me Cannot read property "map" of null probably because powers is null. That means that React.Suspense isn't working as it should. Can anybody help me on this?
For suspense to have any effect, a component farther down the tree needs to throw a promise. When that happens, suspense will catch it and display the fallback until the promise resolves, and then it resumes rendering its normal children. Your code doesn't throw any promises, so suspense doesn't do anything.
So if you want to use suspense for this, you need to have your component throw a promise during rendernig if it detects it doesn't have the data. Then do your fetching, and save data such that when the component mounts again it will have the data (you can't set state, because the component doesn't exist during this time, the fallback does).
const App = () => (
<React.Suspense fallback={<p>Loading</p>}>
<RoutesPowers />
</React.Suspense>
)
let savedPowers = null;
const fetchPowers = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
savedPowers = ['first', 'second']
resolve();
}, 3000)
});
}
const RoutesPowers = () => {
const [powers, setPowers] = React.useState(savedPowers);
if (!powers) {
throw fetchPowers();
}
return powers.map(value => <div key={value}>{value}</div>);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.development.js"></script>
<div id="root"></div>
Be aware that it's uncommon to use this pattern. More common is to handle it all in the one component, rendering a placeholder if there is no data, then kicking off the fetch in an effect, then updating state when it's done. Your current code is almost there, you'd just want to delete the <Suspense> and add code inside RoutesPowers to return the loading paragraph.
const RoutesPowers = () => {
const [powers, setPowers] = useState(null);
const fetchPowers = () => setTimeout(() => setPowers(Powers), 3000);
useEffect(() => fetchPowers(), []);
if (!powers) {
return <p>loading</p>
}
return ( powers.map(route => <RoutePowers route={route}/> )
};

clear timeout in react if component state changes

I have code using react hooks that is fetching some data from an API after a search value has been entered.
I am trying to activate a Timeout that will stop in case the value of const [searchResults, setSearchResults] = useState([]);changes.
I am not able to find out the way to do it, I can activate it when the use effect for fetching the information is activated, but I can not deactivate it in case new information is found.
In a nutshell:
I would like to know how to clearTimeout in case searchResults has value.
My code looks like:
useEffect(() => {
setIsLoading(true);
ProductsApi.getSearchProducts(query,setSearchResults, setIsLoading);
setTimeout(() => {
setError(false)
}, 2000);
}, [query]);
useEffect(() => {
clearTimeout(timer);
}, [searchResults]);
A generic answer to your problem
const MyComponent = () => {
const [shouldRun, setShouldRun] = useState(true);
useEffect(() => {
const TIMEOUT_DURATION = 10000;
const myTimeoutCallback = () => {
if (!shouldRun) return;
// Add your logic here
console.log("My callback was invoked after a delay.");
};
const timeoutId = setTimeout(myTimeoutCallback, TIMEOUT_DURATION);
return () => clearTimeout(timeoutId);
}, [shouldRun]);
};
You can use shouldRun as a condition if the callback function should be invoked or not.
To clear the time out you can do this: const timer = setTimeout(() => {.
However with your code, timer will be out of scope when you call clearTimeout(timer).
You should adjust your code so that timer is in scope allowing access to the variable timer.
Use setInterval
function DemoApp() {
React.useEffect(() => {
const timer = window.setInterval(() => {
console.log('2 seconds has passed');
}, 2000);
return () => {
window.clearInterval(timer);
};
}, []);
return (
<div>
My Demo Timer | Please check console.
</div>
);
}
ReactDOM.render(
<div>
<DemoApp />
</div>,
document.querySelector("#DemoApp")
);
<script src="https://unpkg.com/react#16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="DemoApp"></div>

React custom Hook using useRef returns null for the first time the calling component Loads?

I have created a custom hook to scroll the element back into view when the component is scrolled.
export const useComponentIntoView = () => {
const ref = useRef();
const {current} = ref;
if (current) {
window.scrollTo(0, current.offsetTop );
}
return ref;
}
Now i am making use of this in a functional component like
<div ref={useComponentIntoView()}>
So for the first time the current always comes null, i understand that the component is still not mounted so the value is null . but what can we do to get this values always in my custom hook as only for the first navigation the component scroll doesn't work . Is there any work around to this problem .
We need to read the ref from useEffect, when it has already been assigned. To call it only on mount, we pass an empty array of dependencies:
const MyComponent = props => {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
}, []);
return <div ref={ref} />;
};
In order to have this functionality out of the component, in its own Hook, we can do it this way:
const useComponentIntoView = () => {
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
}, []);
return ref;
};
const MyComponent = props => {
const ref = useComponentIntoView();
return <div ref={ref} />;
};
We could also run the useEffect hook after a certain change. In this case we would need to pass to its array of dependencies, a variable that belongs to a state. This variable can belong to the same Component or an ancestor one. For example:
const MyComponent = props => {
const [counter, setCounter] = useState(0);
const ref = useRef(null);
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop);
}
}, [counter]);
return (
<div ref={ref}>
<button onClick={() => setCounter(counter => counter + 1)}>
Click me
</button>
</div>
);
};
In the above example each time the button is clicked it updates the counter state. This update triggers a new render and, as the counter value changed since the last time useEffect was called, it runs the useEffect callback.
As you mention, ref.current is null until after the component is mounted. This is where you can use useEffect - which will fire after the component is mounted, i.e.:
const useComponentIntoView = () => {
const ref = useRef();
useEffect(() => {
if (ref.current) {
window.scrollTo(0, ref.current.offsetTop );
}
});
return ref;
}

React Hook useEffect has a missing dependency: 'dispatch'

This is my first time working with react js , im trying to remove the alert when leaving this view cause i don't want to show it on the other view but in case that there is no error i want to keep the success alert to show it when i'm gonna redirect to the other view
but im getting this wearning on google chrome
Line 97:6: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array react-hooks/exhaustive-deps
if i did include dispatch i get infinite loop
const [state, dispatch] = useUserStore();
useEffect(() => {
let token = params.params.token;
checktoken(token, dispatch);
}, [params.params.token]);
useEffect(() => {
return () => {
if (state.alert.msg === "Error") {
dispatch({
type: REMOVE_ALERT
});
}
};
}, [state.alert.msg]);
//response from the api
if (!token_valide || token_valide_message === "done") {
return <Redirect to="/login" />;
}
this is useUserStore
const globalReducers = useCombinedReducers({
alert: useReducer(alertReducer, alertInitState),
auth: useReducer(authReducer, authInitState),
register: useReducer(registerReducer, registerInitState),
token: useReducer(passeditReducer, tokenvalidationInitState)
});
return (
<appStore.Provider value={globalReducers}>{children}</appStore.Provider>
);
};
export const useUserStore = () => useContext(appStore);
UPDATE 09/11/2020
This solution is no longer needed on eslint-plugin-react-hooks#4.1.0 and above.
Now useMemo and useCallback can safely receive referential types as dependencies.#19590
function MyComponent() {
const foo = ['a', 'b', 'c']; // <== This array is reconstructed each render
const normalizedFoo = useMemo(() => foo.map(expensiveMapper), [foo]);
return <OtherComponent foo={normalizedFoo} />
}
Here is another example of how to safely stabilize(normalize) a callback
const Parent = () => {
const [message, setMessage] = useState('Greetings!')
return (
<h3>
{ message }
</h3>
<Child setter={setMessage} />
)
}
const Child = ({
setter
}) => {
const stableSetter = useCallback(args => {
console.log('Only firing on mount!')
return setter(args)
}, [setter])
useEffect(() => {
stableSetter('Greetings from child\'s mount cycle')
}, [stableSetter]) //now shut up eslint
const [count, setCount] = useState(0)
const add = () => setCount(c => c + 1)
return (
<button onClick={add}>
Rerender {count}
</button>
)
}
Now referential types with stable signature such as those provenients from useState or useDispatch can safely be used inside an effect without triggering exhaustive-deps even when coming from props
---
Old answer
dispatch comes from a custom hook so it doesn't have an stable signature therefore will change on each render (reference equality). Add an aditional layer of dependencies by wrapping the handler inside an useCallback hook
const [foo, dispatch] = myCustomHook()
const stableDispatch = useCallback(dispatch, []) //assuming that it doesn't need to change
useEffect(() =>{
stableDispatch(foo)
},[stableDispatch])
useCallback and useMemo are helper hooks with the main purpose off adding an extra layer of dependency check to ensure synchronicity. Usually you want to work with useCallback to ensure a stable signature to a prop that you know how will change and React doesn't.
A function(reference type) passed via props for example
const Component = ({ setParentState }) =>{
useEffect(() => setParentState('mounted'), [])
}
Lets assume you have a child component which uppon mounting must set some state in the parent (not usual), the above code will generate a warning of undeclared dependency in useEffect, so let's declare setParentState as a dependency to be checked by React
const Component = ({ setParentState }) =>{
useEffect(() => setParentState('mounted'), [setParentState])
}
Now this effect runs on each render, not only on mounting, but on each update. This happens because setParentState is a function which is recreated every time the function Component gets called. You know that setParentState won't change it's signature overtime so it's safe to tell React that. By wrapping the original helper inside an useCallback you're doing exactly that (adding another dependency check layer).
const Component = ({ setParentState }) =>{
const stableSetter = useCallback(() => setParentState(), [])
useEffect(() => setParentState('mounted'), [stableSetter])
}
There you go. Now React knows that stableSetter won't change it's signature inside the lifecycle therefore the effect do not need too run unecessarily.
On a side note useCallback it's also used like useMemo, to optmize expensive function calls (memoization).
The two mai/n purposes of useCallback are
Optimize child components that rely on reference equality to prevent unnecessary
renders. Font
Memoize expensive calculations
I think you can solve the problem at the root but that means changing useCombinedReducers, I forked the repo and created a pull request because I don't think useCombinedReducers should return a new reference for dispatch every time you call it.
function memoize(fn) {
let lastResult,
//initial last arguments is not going to be the same
// as anything you will pass to the function the first time
lastArguments = [{}];
return (...currentArgs) => {
//returning memoized function
//check if currently passed arguments are the same as
// arguments passed last time
const sameArgs =
currentArgs.length === lastArguments.length &&
lastArguments.reduce(
(result, lastArg, index) =>
result && Object.is(lastArg, currentArgs[index]),
true,
);
if (sameArgs) {
//current arguments are same as last so just
// return the last result and don't execute function
return lastResult;
}
//current arguments are not the same as last time
// or function called for the first time, execute the
// function and set last result
lastResult = fn.apply(null, currentArgs);
//set last args to current args
lastArguments = currentArgs;
//return result
return lastResult;
};
}
const createDispatch = memoize((...dispatchers) => action =>
dispatchers.forEach(fn => fn(action)),
);
const createState = memoize(combinedReducers =>
Object.keys(combinedReducers).reduce(
(acc, key) => ({ ...acc, [key]: combinedReducers[key][0] }),
{},
),
);
const useCombinedReducers = combinedReducers => {
// Global State
const state = createState(combinedReducers);
const dispatchers = Object.values(combinedReducers).map(
([, dispatch]) => dispatch,
);
// Global Dispatch Function
const dispatch = createDispatch(...dispatchers);
return [state, dispatch];
};
export default useCombinedReducers;
Here is a working example:
const reduceA = (state, { type }) =>
type === 'a' ? { count: state.count + 1 } : state;
const reduceC = (state, { type }) =>
type === 'c' ? { count: state.count + 1 } : state;
const state = { count: 1 };
function App() {
const [a, b] = React.useReducer(reduceA, state);
const [c, d] = React.useReducer(reduceC, state);
//memoize what is passed to useCombineReducers
const obj = React.useMemo(
() => ({ a: [a, b], c: [c, d] }),
[a, b, c, d]
);
//does not do anything with reduced state
const [, reRender] = React.useState();
const [s, dispatch] = useCombinedReducers(obj);
const rendered = React.useRef(0);
const [sc, setSc] = React.useState(0);
const [dc, setDc] = React.useState(0);
rendered.current++;//display how many times this is rendered
React.useEffect(() => {//how many times state changed
setSc(x => x + 1);
}, [s]);
React.useEffect(() => {//how many times dispatch changed
setDc(x => x + 1);
}, [dispatch]);
return (
<div>
<div>rendered {rendered.current} times</div>
<div>state changed {sc} times</div>
<div>dispatch changed {dc} times</div>
<button type="button" onClick={() => reRender({})}>
re render
</button>
<button
type="button"
onClick={() => dispatch({ type: 'a' })}
>
change a
</button>
<button
type="button"
onClick={() => dispatch({ type: 'c' })}
>
change c
</button>
<pre>{JSON.stringify(s, undefined, 2)}</pre>
</div>
);
}
function memoize(fn) {
let lastResult,
//initial last arguments is not going to be the same
// as anything you will pass to the function the first time
lastArguments = [{}];
return (...currentArgs) => {
//returning memoized function
//check if currently passed arguments are the same as
// arguments passed last time
const sameArgs =
currentArgs.length === lastArguments.length &&
lastArguments.reduce(
(result, lastArg, index) =>
result && Object.is(lastArg, currentArgs[index]),
true
);
if (sameArgs) {
//current arguments are same as last so just
// return the last result and don't execute function
return lastResult;
}
//current arguments are not the same as last time
// or function called for the first time, execute the
// function and set last result
lastResult = fn.apply(null, currentArgs);
//set last args to current args
lastArguments = currentArgs;
//return result
return lastResult;
};
}
const createDispatch = memoize((...dispatchers) => action =>
dispatchers.forEach(fn => fn(action))
);
const createState = memoize(combinedReducers =>
Object.keys(combinedReducers).reduce(
(acc, key) => ({
...acc,
[key]: combinedReducers[key][0],
}),
{}
)
);
const useCombinedReducers = combinedReducers => {
// Global State
const state = createState(combinedReducers);
const dispatchers = Object.values(combinedReducers).map(
([, dispatch]) => dispatch
);
// Global Dispatch Function
const dispatch = createDispatch(...dispatchers);
return [state, dispatch];
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Resources