According to the docs:
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
We can use the new useEffect() hook to simulate componentDidUpdate(), but it seems like useEffect() is being ran after every render, even the first time. How do I get it to not run on initial render?
As you can see in the example below, componentDidUpdateFunction is printed during the initial render but componentDidUpdateClass was not printed during the initial render.
function ComponentDidUpdateFunction() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
class ComponentDidUpdateClass extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
componentDidUpdate() {
console.log("componentDidUpdateClass");
}
render() {
return (
<div>
<p>componentDidUpdateClass: {this.state.count} times</p>
<button
onClick={() => {
this.setState({ count: this.state.count + 1 });
}}
>
Click Me
</button>
</div>
);
}
}
ReactDOM.render(
<div>
<ComponentDidUpdateFunction />
<ComponentDidUpdateClass />
</div>,
document.querySelector("#app")
);
<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="app"></div>
We can use the useRef hook to store any mutable value we like, so we could use that to keep track of if it's the first time the useEffect function is being run.
If we want the effect to run in the same phase that componentDidUpdate does, we can use useLayoutEffect instead.
Example
const { useState, useRef, useLayoutEffect } = React;
function ComponentDidUpdateFunction() {
const [count, setCount] = useState(0);
const firstUpdate = useRef(true);
useLayoutEffect(() => {
if (firstUpdate.current) {
firstUpdate.current = false;
return;
}
console.log("componentDidUpdateFunction");
});
return (
<div>
<p>componentDidUpdateFunction: {count} times</p>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click Me
</button>
</div>
);
}
ReactDOM.render(
<ComponentDidUpdateFunction />,
document.getElementById("app")
);
<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="app"></div>
You can turn it into custom hooks, like so:
import React, { useEffect, useRef } from 'react';
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
if (didMount.current) func();
else didMount.current = true;
}, deps);
}
export default useDidMountEffect;
Usage example:
import React, { useState, useEffect } from 'react';
import useDidMountEffect from '../path/to/useDidMountEffect';
const MyComponent = (props) => {
const [state, setState] = useState({
key: false
});
useEffect(() => {
// you know what is this, don't you?
}, []);
useDidMountEffect(() => {
// react please run me if 'key' changes, but not on initial render
}, [state.key]);
return (
<div>
...
</div>
);
}
// ...
I made a simple useFirstRender hook to handle cases like focussing a form input:
import { useRef, useEffect } from 'react';
export function useFirstRender() {
const firstRender = useRef(true);
useEffect(() => {
firstRender.current = false;
}, []);
return firstRender.current;
}
It starts out as true, then switches to false in the useEffect, which only runs once, and never again.
In your component, use it:
const firstRender = useFirstRender();
const phoneNumberRef = useRef(null);
useEffect(() => {
if (firstRender || errors.phoneNumber) {
phoneNumberRef.current.focus();
}
}, [firstRender, errors.phoneNumber]);
For your case, you would just use if (!firstRender) { ....
Same approach as Tholle's answer, but using useState instead of useRef.
const [skipCount, setSkipCount] = useState(true);
...
useEffect(() => {
if (skipCount) setSkipCount(false);
if (!skipCount) runYourFunction();
}, [dependencies])
EDIT
While this also works, it involves updating state which will cause your component to re-render. If all your component's useEffect calls (and also all of its children's) have a dependency array, this doesn't matter. But keep in mind that any useEffect without a dependency array (useEffect(() => {...}) will be run again.
Using and updating useRef will not cause any re-renders.
#ravi, yours doesn't call the passed-in unmount function. Here's a version that's a little more complete:
/**
* Identical to React.useEffect, except that it never runs on mount. This is
* the equivalent of the componentDidUpdate lifecycle function.
*
* #param {function:function} effect - A useEffect effect.
* #param {array} [dependencies] - useEffect dependency list.
*/
export const useEffectExceptOnMount = (effect, dependencies) => {
const mounted = React.useRef(false);
React.useEffect(() => {
if (mounted.current) {
const unmount = effect();
return () => unmount && unmount();
} else {
mounted.current = true;
}
}, dependencies);
// Reset on unmount for the next mount.
React.useEffect(() => {
return () => mounted.current = false;
}, []);
};
a simple way is to create a let, out of your component and set in to true.
then say if its true set it to false then return (stop) the useEffect function
like that:
import { useEffect} from 'react';
//your let must be out of component to avoid re-evaluation
let isFirst = true
function App() {
useEffect(() => {
if(isFirst){
isFirst = false
return
}
//your code that don't want to execute at first time
},[])
return (
<div>
<p>its simple huh...</p>
</div>
);
}
its Similar to #Carmine Tambasciabs solution but without using state :)
function useEffectAfterMount(effect, deps) {
const isMounted = useRef(false);
useEffect(() => {
if (isMounted.current) return effect();
else isMounted.current = true;
}, deps);
// reset on unmount; in React 18, components can mount again
useEffect(() => {
isMounted.current = false;
});
}
We need to return what comes back from effect(), because it might be a cleanup function. But we don't need to determine if it is or not. Just pass it on and let useEffect figure it out.
In an earlier version of this post I said resetting the ref (isMounted.current = false) wasn't necessary. But in React 18 it is, because components can remount with their previous state (thanks #Whatabrain).
I thought creating a custom hook would be overkill and I didn't want to muddle my component's readability by using the useLayoutEffect hook for something unrelated to layouts, so, in my case, I simply checked to see if the value of my stateful variable selectedItem that triggers the useEffect callback is its original value in order to determine if it's the initial render:
export default function MyComponent(props) {
const [selectedItem, setSelectedItem] = useState(null);
useEffect(() => {
if(!selectedItem) return; // If selected item is its initial value (null), don't continue
//... This will not happen on initial render
}, [selectedItem]);
// ...
}
This is the best implementation I've created so far using typescript. Basically, the idea is the same, using the Ref but I'm also considering the callback returned by useEffect to perform cleanup on component unmount.
import {
useRef,
EffectCallback,
DependencyList,
useEffect
} from 'react';
/**
* #param effect
* #param dependencies
*
*/
export default function useNoInitialEffect(
effect: EffectCallback,
dependencies?: DependencyList
) {
//Preserving the true by default as initial render cycle
const initialRender = useRef(true);
useEffect(() => {
let effectReturns: void | (() => void) = () => {};
// Updating the ref to false on the first render, causing
// subsequent render to execute the effect
if (initialRender.current) {
initialRender.current = false;
} else {
effectReturns = effect();
}
// Preserving and allowing the Destructor returned by the effect
// to execute on component unmount and perform cleanup if
// required.
if (effectReturns && typeof effectReturns === 'function') {
return effectReturns;
}
return undefined;
}, dependencies);
}
You can simply use it, as usual as you use the useEffect hook but this time, it won't run on the initial render. Here is how you can use this hook.
useNoInitialEffect(() => {
// perform something, returning callback is supported
}, [a, b]);
If you use ESLint and want to use the react-hooks/exhaustive-deps rule for this custom hook:
{
"rules": {
// ...
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "useNoInitialEffect"
}]
}
}
#MehdiDehghani, your solution work perfectly fine, one addition you have to do is on unmount, reset the didMount.current value to false. When to try to use this custom hook somewhere else, you don't get cache value.
import React, { useEffect, useRef } from 'react';
const useDidMountEffect = (func, deps) => {
const didMount = useRef(false);
useEffect(() => {
let unmount;
if (didMount.current) unmount = func();
else didMount.current = true;
return () => {
didMount.current = false;
unmount && unmount();
}
}, deps);
}
export default useDidMountEffect;
Simplified implementation
import { useRef, useEffect } from 'react';
function MyComp(props) {
const firstRender = useRef(true);
useEffect(() => {
if (firstRender.current) {
firstRender.current = false;
} else {
myProp = 'some val';
};
}, [props.myProp])
return (
<div>
...
</div>
)
}
You can use custom hook to run use effect after mount.
const useEffectAfterMount = (cb, dependencies) => {
const mounted = useRef(true);
useEffect(() => {
if (!mounted.current) {
return cb();
}
mounted.current = false;
}, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
};
Here is the typescript version:
const useEffectAfterMount = (cb: EffectCallback, dependencies: DependencyList | undefined) => {
const mounted = useRef(true);
useEffect(() => {
if (!mounted.current) {
return cb();
}
mounted.current = false;
}, dependencies); // eslint-disable-line react-hooks/exhaustive-deps
};
For people who are having trouble with React 18 strict mode calling the useeffect on the initial render twice, try this:
// The init variable is necessary if your state is an object/array, because the == operator compares the references, not the actual values.
const init = [];
const [state, setState] = useState(init);
const dummyState = useRef(init);
useEffect(() => {
// Compare the old state with the new state
if (dummyState.current == state) {
// This means that the component is mounting
} else {
// This means that the component updated.
dummyState.current = state;
}
}, [state]);
Works in development mode...
function App() {
const init = [];
const [state, setState] = React.useState(init);
const dummyState = React.useRef(init);
React.useEffect(() => {
if (dummyState.current == state) {
console.log('mount');
} else {
console.log('update');
dummyState.current = state;
}
}, [state]);
return (
<button onClick={() => setState([...state, Math.random()])}>Update state </button>
);
}
ReactDOM.createRoot(document.getElementById("app")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id="app"></div>
And in production.
function App() {
const init = [];
const [state, setState] = React.useState(init);
const dummyState = React.useRef(init);
React.useEffect(() => {
if (dummyState.current == state) {
console.log('mount');
} else {
console.log('update');
dummyState.current = state;
}
}, [state]);
return (
<button onClick={() => setState([...state, Math.random()])}>Update state </button>
);
}
ReactDOM.createRoot(document.getElementById("app")).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
<div id="app"></div>
If you want to skip the first render, you can create a state "firstRenderDone" and set it to true in the useEffect with empty dependecy list (that works like a didMount). Then, in your other useEffect, you can check if the first render was already done before doing something.
const [firstRenderDone, setFirstRenderDone] = useState(false);
//useEffect with empty dependecy list (that works like a componentDidMount)
useEffect(() => {
setFirstRenderDone(true);
}, []);
// your other useEffect (that works as componetDidUpdate)
useEffect(() => {
if(firstRenderDone){
console.log("componentDidUpdateFunction");
}
}, [firstRenderDone]);
All previous are good, but this can be achieved in a simplier way considering that the action in useEffect can be "skipped" placing an if condition(or any other ) that is basically not run first time, and still with the dependency.
For example I had the case of :
Load data from an API but my title has to be "Loading" till the date were not there, so I have an array, tours that is empty at beginning and show the text "Showing"
Have a component rendered with different information from those API.
The user can delete one by one those info, even all making the tour array empty again as the beginning but this time the API fetch is been already done
Once the tour list is empty by deleting then show another title.
so my "solution" was to create another useState to create a boolean value that change only after the data fetch making another condition in useEffect true in order to run another function that also depend on the tour length.
useEffect(() => {
if (isTitle) {
changeTitle(newTitle)
}else{
isSetTitle(true)
}
}, [tours])
here my App.js
import React, { useState, useEffect } from 'react'
import Loading from './Loading'
import Tours from './Tours'
const url = 'API url'
let newTours
function App() {
const [loading, setLoading ] = useState(true)
const [tours, setTours] = useState([])
const [isTitle, isSetTitle] = useState(false)
const [title, setTitle] = useState("Our Tours")
const newTitle = "Tours are empty"
const removeTours = (id) => {
newTours = tours.filter(tour => ( tour.id !== id))
return setTours(newTours)
}
const changeTitle = (title) =>{
if(tours.length === 0 && loading === false){
setTitle(title)
}
}
const fetchTours = async () => {
setLoading(true)
try {
const response = await fetch(url)
const tours = await response.json()
setLoading(false)
setTours(tours)
}catch(error) {
setLoading(false)
console.log(error)
}
}
useEffect(()=>{
fetchTours()
},[])
useEffect(() => {
if (isTitle) {
changeTitle(newTitle)
}else{
isSetTitle(true)
}
}, [tours])
if(loading){
return (
<main>
<Loading />
</main>
)
}else{
return (
<main>
<Tours tours={tours} title={title} changeTitle={changeTitle}
removeTours={removeTours} />
</main>
)
}
}
export default App
const [dojob, setDojob] = useState(false);
yourfunction(){
setDojob(true);
}
useEffect(()=>{
if(dojob){
yourfunction();
setDojob(false);
}
},[dojob]);
I'm retrieving some data from an API using useEffect, and I want to be able to filter that returned data using a prop being fed into the component from its parent.
I'm trying to filter the state after it is set by useEffect, however it looks like the component is going into an infinite render loop.
What do I need to do to prevent this?
export default function HomeJobList(props: Props): ReactElement {
const [listings, setListings] = React.useState(null);
useEffect(() => {
const func = async () => {
let res = await service.getListings();
setListings(res);
};
func();
}, []);
if (props.searchTerm && listings) {
let filtered = listings.filter((x) => x.positionTitle.includes(props.searchTerm));
setListings(filtered);
}
return (
<>
<div>do stuff</div>
</>
);
}
I understand that the use of the setListing function is then causing a rerender after the filtering, which then causes another setListing call. But what's the best way to break this loop?
Should I just have another state value that maintains the last searchTerm used to filter and check against that before filtering?
Or is there a better way?
It's an indinite loop because every time you filter, you set it as a state variable, which causes re-rendering and filtering & setting the variable again - thus a loop.
I suggest you do it all in one place (your useEffect is a good place for that, because it only executes once.
useEffect(() => {
(async () => {
const res = await service.getListings();
const filtered = res.filter((x) => x.positionTitle.includes(props.searchTerm));
setListings(filtered);
})();
}, []);
When the state changes that trigger a re-render, that's why you have an infinite loop; what you have to do is to wrap your filtering in a useEffectthat that depends on the searchTerm prop, like this:
import React, { useEffect } from 'react';
export default function HomeJobList() {
const [listings, setListings] = React.useState(null);
useEffect(() => {
const func = async () => {
let res = await service.getListings();
setListings(res);
};
func();
}, []);
useEffect(() => {
if (listings) {
let filtered = listings.filter(x =>
x.positionTitle.includes(props.searchTerm)
);
setListings(filtered);
}
}, [props.searchTerm]);
return (
<>
<div>do stuff</div>
</>
);
}
You need to create a function that's called inside the JSX you're returning.
Actually, you'll need to render the component every time the Props objects changes. That's achieved by calling the function in the JSX code.
Example:
Function:
const filteredListings = () => {
if (props.searchTerm && listings) {
let filtered = listings.filter((x) => {
x.positionTitle.includes(props.searchTerm));
}
return filtered;
}
}
Return Statement:
return (
<ul>
{
filteredListings().map((listing) =>
<li>{listing.title}</li>
);
}
</ul>
);
What you need is a useEffect which does the filtering when props changes.
Replace this
if (props.searchTerm && listings) {
let filtered = listings.filter((x) => x.positionTitle.includes(props.searchTerm));
setListings(filtered);
}
with
useEffect(()=>{
if (props.searchTerm) {
setListings(prevListing => {
return prevListing.filter((x) => x.positionTitle.includes(props.searchTerm))
});
}
}, [props.searchTerm] )
I have a function which is async and returns a value.
How do I get this value when I call that function within a React function component?
For me it always shows [object Promise].
I already tried some stuff with the Effect Hook.
function Home() {
const { publicKey } = useWallet();
const [buttonClicked, setClick] = useState(false);
let tokenAccounts;
useEffect(() => {
if (buttonClicked) {
//This is the async function that I am calling
tokenAccounts = getTokenAccounts(publicKey);
console.log("token account: " + tokenAccounts);
readyToShow = true;
}
})
function handleButClick() {
setClick(true);
}
let display;
if (buttonClicked) {
display = <div>test{tokenAccounts}</div>
} else {
display = (publicKey && <button onClick={handleButClick}>click</button>);
}
return (
<div>
{display}
</div>
);
}
(It shows button and after the button is clicked it does show test and should also show the variable tokeAccounts which in my case is a [object Promise])
Putting an await in front of the function call would be my intentional solution but then it says Unexpected reserved word 'await'
Try this:
const Home = () => {
const { publicKey } = useWallet();
const [tokenAccounts, setTokenAccounts] = useState(undefined);
const handleButClick = () => {
getTokenAccounts(publicKey)
.then(result => setTokenAccounts(result));
// Depending on API may need result.data or other
}
return (
<React.Fragment>
{tokenAccounts === undefined && publicKey &&
<button onClick={handleButClick}>click</button>
}
{tokenAccounts && <div>test{tokenAccounts}</div>}
</React.Fragment>
);
}
When the component first loads the tokenAccounts state variable is undefined so your button element will be displayed. When the button is clicked the event handler calls your async action and accesses the return value via the .then statement (also check out .catch and .finally). The tokenAccounts state variable is then set and the state change causes the component to refresh. Since tokenAccounts now has a value it is displayed and the button element hidden.
function Home() {
const { publicKey } = useWallet();
const [buttonClicked, setClick] = useState(false);
let tokenAccounts;
useEffect(() => {
const getTokenAccountsLocally = async () => {
if (buttonClicked) {
tokenAccounts = await getTokenAccounts(publicKey);
console.log("token account: " + tokenAccounts);
}
}
getTokenAccountsLocally();
})
function handleButClick() {
setClick(true);
}
let display;
if (buttonClicked) {
//runs through this before tokenAccounts is loaded with the value
display = <div>this is the {tokenAccounts}</div>
} else {
display = (publicKey && <button onClick={handleButClick}>click</button>);
}
return (
<div>
{display}
</div>
);
}
Wrapping the async function call around another async function locally and then call it so I can add wait for the other async function call kind of works. tokenAccounts is now loaded with the returned value from the async function call. BUT it gets shown before it actually loaded the value.
I am new to React and I tried to toggle the Login/Logout based on the current state of authentication. I've used Google OAuth to perform the authentication.
I have a state variable to say if the user is authenticated or not and is defaulted to false. Upon successful authentication, I set the state to true.
Now the problem is, after completing a successful authentication, when I refresh the screen, the screen reloads and I see the console.log printing false and login appears momentarily. And after a second the console.log prints true and then the logout appears. How do I avoid showing login screen (for that one second after refreshing the screen) when the authentication is completed? Can someone help me please? Thanks.
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
setIsAuthenticated(false)
}, [])
const handleSuccessAuth = x => {
setIsAuthenticated(true)
}
const handleFailureAuth = x => {
setIsAuthenticated(false)
}
const handleLogout = x => {
setIsAuthenticated(false)
}
console.log(isAuthenticated)
if(!isAuthenticated)
{
return (
<div>
<LoginView
handleSuccessAuth = {handleSuccessAuth}
handleFailureAuth = {handleFailureAuth}
/>
</div>
)
}
else
{
return (
<div>
<LogoutView
handleLogout = {handleLogout}
/>
</div>)
}
If your variable goes from false to true it means your code is doing something, probably an AJAX call, my recommendation is to show a loading scree/message until the AJAX request is completed.
There is no way to keep the variable intact on reload but you can keep a variable that tracks if the user authentication has been initialized and show a loading indicator in the meantime
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [authLoaded, setAuthLoaded] = useState(false)
// this does nothing, passing false to useState above sets the initial value
// useEffect(() => {
// setIsAuthenticated(false)
// }, [])
const handleSuccessAuth = x => {
setIsAuthenticated(true)
setAuthLoaded(true)
}
const handleFailureAuth = x => {
setIsAuthenticated(false)
setAuthLoaded(true)
}
const handleLogout = x => {
setIsAuthenticated(false)
}
console.log(isAuthenticated)
if (!authLoaded) {
return <div>loading...</div>
}
if(!isAuthenticated)
{
return (
<div>
<LoginView
handleSuccessAuth = {handleSuccessAuth}
handleFailureAuth = {handleFailureAuth}
/>
</div>
)
}
else
{
return (
<div>
<LogoutView
handleLogout = {handleLogout}
/>
</div>)
}
I believe olivier-boisse alluded to using localStorage to persist your state. You can use an useEffect hook to persist your isAuthenticated to localStorage when the value updates, and use a state initializer function to read in the initial state from local storage.
const [isAuthenticated, setIsAuthenticated] = useState(() => {
return !!JSON.parse(localStorage.getItem('auth');
});
useEffect(() => {
localStorage.setItem('auth', JSON.stringify(isAuthenticated));
}, [isAuthenticated]);
Good afternoon,
I am attempting to set and clear an interval. I assign the interval to my state because attempting to declare it anywhere else either isn't allowed (when declared outside of a function) or is limited by scope (when declared inside of a function) or is otherwise inaccessible (when declared outside of the class). My code is as follows (It's still very much in the testing stage so it's pretty rough. It is doing what I want it to though, short of clearing the interval):
import React, { Component, lazy, Suspense } from 'react';
const Passersby = lazy(() => import('../components/Passersby'));
class Public extends Component {
state = {
passersby: null,
intervalStorer: null
};
startJeff = () => {
this.setState({ passersby: null });
import('axios').then(axios => {
axios.get('http://localhost:8080/get_jeff')
});
setTimeout(this.stopIt, 10000);
//remember to call clearTimeout() if defeat conditions are satisfied
this.checkForJeff();
}
checkForJeff = () => {
if (this.state.passersby === null) {
this.setState({ passersby: [] });
}
this.queryForJeff();
}
queryForJeff = () => {
//setInterval() returns an numerical code, correct? Why isn't it being stored here?
const interval = setInterval(this.assignJeff, 1000);
this.setState({ intervalStorer: interval });
}
assignJeff = () => {
console.log('looked for jeff')
import('axios').then(axios => {
axios.get('http://localhost:8080/get_jeff/more_jeffs')
.then(response => {
const folks = response.data;
const updatePassersby = this.state.passersby;
updatePassersby.push.apply(updatePassersby, folks);
this.setState({ passersby: updatePassersby });
});
});
}
stopIt = () => {
//this logs in the console as "undefined"
console.log(this.intervalStorer);
clearInterval(this.intervalStorer);
import('axios').then(axios => {
axios.get('http://localhost:8080/get_jeff/stop_jeff')
});
}
render() {
let people = null;
if (this.state.passersby) {
people = (
<Passersby
name={this.state.passersby.name}
activity={this.state.passersby.activity}
key={this.state.passersby.id}
passersby={this.state.passersby}
/>
)
}
return <div>
<h1>Jeffs?</h1>
<button onClick={this.startJeff}>Start the Jeffing</button>
<button onClick={this.checkForJeff}>More Possible Jeffs?</button>
<button onClick={this.postInterval}>Interval Test</button>
<button onClick={this.stopIt}>NO MORE JEFFS</button>
<Suspense fallback={<div>Jeff Could Be Anywhere...</div>}>
{people}
</Suspense>
</div>
}
}
export default Public;
What do I need to do to get the setInterval() stored properly in my state?
Thanks.
You are accessing your state variable incorrectly,
access it as
this.state.intervalStorer
this.intervalStorer is considered as an uninitialized local variable, that's why it is returning you undefined.