How to stop initial render for useEffect hook - javascript

Earlier I had a Class component, so I didn't face any issues while using lifecycle methods, but after converting to useEffect hooks, I am facing the initial render issue which I don't want to happen.
Class
componentDidMount() {
this.setState({
patchVal:this.props.patchTaskVal,
startTime:this.props.patchStartTime,
setEndTime:this.props.patchEndTime
})
}
componentDidUpdate(prevProps) {
if (prevProps.patchTaskVal !== this.props.patchTaskVal) {
this.callValidation()
}
if (prevProps.closeTask !== this.props.closeTask) {
this.setState({
showValue:false,
progressValue:[],
startTime:new Date(),
setEndTime:""
})
}
if (prevProps.patchStartTime !== this.props.patchStartTime || prevProps.endTime !== this.props.endTime && this.props.endTime !== "") {
this.setState({
startTime:this.props.patchStartTime,
setEndTime:parseInt(this.props.endTime)
})
}
}
Functional
const [patchTaskVal, setPatchTaskVal]=useState(/*initial value */)
const [startTime, setStartTime]=useState()
const [endTime, setEndTime] = useState()
**// I want only this useEffect to run on the initial render**
useEffect(() => {
setPatchTaskVal(props.patchTaskVal)
...//set other states
}, [])
useEffect(() => {
callValidation()
}, [props.patchTaskVal])
useEffect(() => {
//setShowValue...
}, [props.closeTask])
useEffect(() => {
if (props.endTime != "") {
// set states...
}
}, [props.patchStartTime,props.endTime])
Here I am facing an issue where all the useEffects are running on the initial render, Please suggest a solution for this so that only the first useEffect will run on the initial render and all other useEffects will run according to its dependency prop values.

You basically need a ref which will tell you whether this is the first render on not. Refs values persist over rerenders. You can start with a truthy value and toggle it to false after the first render (using a useEffect with an empty array[]). Based on that you can run your desired code.
You can also put the whole thing in a custom hook:
import { useEffect, useRef } from "react";
const useOnUpdate = (callback, deps) => {
const isFirst = useRef(true);
useEffect(() => {
if (!isFirst.current) {
callback();
}
}, deps);
useEffect(() => {
isFirst.current = false;
}, []);
};
export default useOnUpdate;
You can call this hook in your component like :
useOnUpdate(() => {
console.log(prop);
}, [prop]);
In the hook:
After the initial render, both useEffects run. But when the first effect runs the value of the isFirst.current is true. So the callback is not called. The second useEffect also runs and sets isFirst.current to false.
Now in subsequent renders only the first useEffect run (when dependencies change), and isFirst.current is false now so callback is executed.
The order of the two useEffects is very important here. Otherwise, in the useEffect with deps, isFirst.current will be true even after the first render.
Link

If you compare the functional and the class component you can notice that there is one part missing - previous props.
Functional component does not have previous props in scope, but you can save them yourself with a small trick: save them to reference so it will not impact you render cycle.
Since now you have the previous props and the current props you can apply the same logic you did for class component.
import React, { useRef, useEffect, useState } from "react";
default function App() {
const [input, setInput] = useState("");
const [commitInput, setCommitInput] = useState("");
return (
<>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<button onClick={() => setCommitInput(input)}>apply</button>
<Child test={commitInput} />
</>
);
}
function Child(props) {
const prev = useRef(props.test);
useEffect(() => {
if (prev.current !== props.test) {
alert("only when changes");
}
}, [props.test]);
return <div>{props.test}</div>;
}

try this...
let init = true;
useEffect( ()=>{
if(init) {
setPatchTaskVal(props.patchTaskVal)
init = false;
...//set other states}
}, [])
useEffect( ()=> {
!init && callValidation()
},[props.patchTaskVal])
useEffect( ()=>{
//!init && setShowValue...
},[props.closeTask])
useEffect( ()=>{
if(props.endTime!="" && !init){
// set states...
}
},[props.patchStartTime,props.endTime])

Hope my understanding is right about your question.
Why not just add a if statement to check the state is not undefined or default value
useEffect( ()=> {
if (props.patchTaskVal) {
callValidation()
}
},[props.patchTaskVal])
useEffect( ()=>{
if (props.closeTask) {
//setShowValue...
}
},[props.closeTask])
useEffect( ()=>{
if(props.patchStartTime){
// set states...
}
if(props.endTime){
// set states...
}
},[props.patchStartTime,props.endTime]
And according your class component,
this.setState({
patchVal:this.props.patchTaskVal,
startTime:this.props.patchStartTime,
setEndTime:this.props.patchEndTime
})
The function component should map props to component's state. Like this
const [patchTaskVal, setPatchTaskVal]=useState(props.patchTaskVal)
const [startTime, setStartTime]=useState(props.patchStartTime)
const [endTime, setEndTime] = useState(props.patchEndTime)

Related

Which is the right way to detect first render in a react component

I have a scenario where I need to detect the first render of a component. Here I have build a small example. Could someone explain to me what is the correct approach?
Why do most of the people suggest to use a ref instead of a plain state.
https://codesandbox.io/s/condescending-burnell-0ex3x?file=/src/App.js
import React, { useState, useRef, useEffect } from "react";
import "./styles.css";
export default function App() {
const firstRender = useDetectFirstRender();
const [random, setRandom] = useState("123");
useEffect(() => {
if (firstRender) {
console.log("first");
} else {
console.log("second");
}
}, [random]);
return (
<div className="App">
<h1>Random Number is {random}</h1>
<button onClick={() => setRandom(Math.random())}>Change Name</button>
</div>
);
}
//Approach 1
// export function useDetectFirstRender() {
// const firstRender = useRef(true);
// useEffect(() => {
// firstRender.current = false;
// }, []);
// return firstRender.current;
// }
//Approach 2
export function useDetectFirstRender() {
const [firstRender, setFirstRender] = useState(true);
useEffect(() => {
setFirstRender(false);
}, []);
return firstRender;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
You could create a reusable custom hook for that, based on useRef.
function useFirstRender() {
const ref = useRef(true);
const firstRender = ref.current;
ref.current = false;
return firstRender;
}
you can detect and save it by using useMemo or useCallback hook. but here the most preferable is useMemo as it prevent the same rendering again and again.
const firstRender = useMemo(
() =>console.log('first Render'),
[]
);
here it will render once and save value in the first Render,so you can use this anywhere where you need.
const firstRender = useRef(true);
useEffect(() => {
if (firstRender.current) {
firstRender.current = false;
return;
}
doSomething()
});
The useEffect hook takes a second parameter. This second param is an array of variables that the component will check ensure they've changed before re-rendering. However, if that array is empty, the hook is only called once during initial render. This is similar to the useMemo() trick posted previously.
useEffect(() => doSomethingOnce(), [])
^^

Converting componentDidMount into useEffect

I am trying to learn React hooks, and trying to convert existing codebase to use hooks, but I am confused.
Is it normal to set state inside useEffect? Would I be causing the dreaded infinite loop if I do so?
import React, { useState, useEffect } from 'react';
import App from 'next/app';
import Layout from './../components/Layout';
function MyApp({ Component, pageProps }) {
const [ cart, setCart ] = useState([]);
const addToCart = (product) => {
setCart((prevCartState) => {
return [ ...prevCartState, product ];
});
localStorage.setItem('cart', JSON.stringify(cart));
};
//mimicking componentDidMount to run some effect using useEffect
//useEffect(() => setCount((currentCount) => currentCount + 1), []);
useEffect(() => {
const cartCache = JSON.parse(localStorage.getItem('cart'));
//cart = cartCache; Good or bad?
cartCache || setCart(() =>{
});
}, []);
return <Component {...pageProps} />;
}
My original class based component:
/*
export default class MyApp extends App {
state = {
cart: []
}
componentDidMount = () => {
const cart = JSON.parse(localStorage.getItem('cart'));
if (cart) {
this.setState({
cart
});
}
};
addToCart = (product) => {
this.setState({
cart: [...this.state.cart, product]
});
localStorage.setItem('cart', JSON.stringify(this.state.cart));
}
render() {
const { Component, pageProps } = this.props
return (
<contextCart.Provider value={{ cart: this.state.cart, addToCart: this.addToCart }}>
<Layout>
<Component {...pageProps} />
</Layout>
</contextCart.Provider>
)
}
}*/
It's okey to set state inside useEffect as long as you don't listen to changes of the same field inside dependency array. In your particular case you are calling useEffect only once (since you have passed an empty dependency array).
useEffect(() => {
const cartCache = JSON.parse(localStorage.getItem('cart'));
if (cartCache) {
setCart(cartCache);
}
}, []);
Also would be cool to add the second useEffect to listen to cart changes and keep the localStorage up-to-date.
useEffect(() => {
localStorage.setItem('cart', JSON.stringify(cart));
}, [cart]);
Because localStorage.getItem() is a synchronous call thus for this scenario you can also use the function callback version of useState in order to set initial value. In this way you don't need to use useEffect. Usually if it is possible I try to avoid introducing any new side effects in my functional components.
You can try as the following instead:
const [ cart, setCart ] = useState(() => {
const cartCache = JSON.parse(localStorage.getItem('cart'));
if (cartCache) {
return cartCache;
}
localStorage.setItem('cart', JSON.stringify([]));
return [];
});
In this way if the cart element is missing from the localStorage the code will create it with a default [] empty array and set it also for your state. Other case it will set your state the value from storage.
Please note: Also I agree with the answer from kind user here in terms of listening cart state changes to keep localStorage up to date with useEffect. My suggestion is only for the initial state.

React hooks - onClick and useEffect

React Hooks is not updating to use the prop passed down and then stored. Usually I would resolve useState issues by calling functionality inside useEffect but in this case I need to update after a click event:
const [currentLayer, setCurrentLayer] = useState();
useEffect(() => {
console.log(props.currentLayer) // props.currentLayer is defined
setCurrentLayer(props.currentLayer);
}, [props.currentLayer]);
useEffect(() => {
console.log(currentLayer); // currentLayer state is defined
}, [currentLayer]);
/*
* Called when the timeline product is clicked
*/
const clickHandler = e => {
console.log(currentLayer); // currentLayer state is undefined
currentLayer.getSource().updateParams({ TIME: e.time });
};
return <Timeline options={props.timelineOptions} items={items} clickHandler={e => clickHandler(e)} />;
When clickHandler is called currentLayer state is undefined despite having been set earlier.
What is the best way to combine useEffect and the clickHandler, or am I missing something else?
import React from 'react'
const Component = (props) => {
// ... your other logic
const [currentLayer, setCurrentLayer] = useState(props.currentLayer)
const clickHandler = e => {
currentLayer.getSource().updateParams({ TIME: e.time });
}
return <Timeline options={props.timelineOptions} items={items} clickHandler={clickHandler} />
}
I don't see a reason why you need the useEffect hook. In fact, you should not set the currentLayer props in this component but rather use it as it is. This is so that when there is a change in the props.currentLayer, this component will also re-render.
const clickHandler = e => {
props.currentLayer.getSource().updateParams({ TIME: e.time });
};

componentWillUnmount with React useEffect hook

How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount?
In a traditional class component I would do something like this:
class Effect extends React.PureComponent {
componentDidMount() { console.log("MOUNT", this.props); }
componentWillUnmount() { console.log("UNMOUNT", this.props); }
render() { return null; }
}
With the useEffect hook:
function Effect(props) {
React.useEffect(() => {
console.log("MOUNT", props);
return () => console.log("UNMOUNT", props)
}, []);
return null;
}
(Full example: https://codesandbox.io/s/2oo7zqzx1n)
This does not work, since the "cleanup" function returned in useEffect captures the props as they were during mount and not state of the props during unmount.
How could I get the latest version of the props in useEffect clean up without running the function body (or cleanup) on every prop change?
A similar question does not address the part of having access to the latest props.
The react docs state:
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.
In this case however I depend on the props... but only for the cleanup part...
You can make use of useRef and store the props to be used within a closure such as render useEffect return callback method
function Home(props) {
const val = React.useRef();
React.useEffect(
() => {
val.current = props;
},
[props]
);
React.useEffect(() => {
return () => {
console.log(props, val.current);
};
}, []);
return <div>Home</div>;
}
DEMO
However a better way is to pass on the second argument to useEffect so that the cleanup and initialisation happens on any change of desired props
React.useEffect(() => {
return () => {
console.log(props.current);
};
}, [props.current]);
useLayoutEffect() is your answer in 2021
useLayoutEffect(() => {
return () => {
// Your code here.
}
}, [])
This is equivalent to ComponentWillUnmount.
99% of the time you want to use useEffect, but if you want to perform any actions before unmounting the DOM then you can use the code I provided.
useLayoutEffect is great for cleaning eventListeners on DOM nodes.
Otherwise, with regular useEffect ref.current will be null on time hook triggered
More on react docs https://reactjs.org/docs/hooks-reference.html#uselayouteffect
import React, { useLayoutEffect, useRef } from 'react';
const audioRef = useRef(null);
useLayoutEffect(() => {
if (!audioRef.current) return;
const progressEvent = (e) => {
setProgress(audioRef.current.currentTime);
};
audioRef.current.addEventListener('timeupdate', progressEvent);
return () => {
try {
audioRef.current.removeEventListener('timeupdate', progressEvent);
} catch (e) {
console.warn('could not removeEventListener on timeupdate');
}
};
}, [audioRef.current]);
Attach ref to component DOM node
<audio ref={audioRef} />
useEffect(() => {
if (elements) {
const cardNumberElement =
elements.getElement('cardNumber') || // check if we already created an element
elements.create('cardNumber', defaultInputStyles); // create if we did not
cardNumberElement.mount('#numberInput');
}
}, [elements]);

How to call a componentDidMount in the functional component [duplicate]

Instead of writing my components inside a class, I'd like to use the function syntax.
How do I override componentDidMount, componentWillMount inside function components?
Is it even possible?
const grid = (props) => {
console.log(props);
let {skuRules} = props;
const componentDidMount = () => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
};
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
Edit: With the introduction of Hooks it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently
Hooks are a new feature proposal that lets you use state and other
React features without writing a class. They are released in React as a part of v16.8.0
useEffect hook can be used to replicate lifecycle behavior, and useState can be used to store state in a function component.
Basic syntax:
useEffect(callbackFunction, [dependentProps]) => cleanupFunction
You can implement your use case in hooks like
const grid = (props) => {
console.log(props);
let {skuRules} = props;
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
useEffect can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behavior of componentWillUnmount:
Eg: componentWillUnmount
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
window.removeEventListener('unhandledRejection', handler);
}
}, [])
To make useEffect conditional on specific events, you may provide it with an array of values to check for changes:
Eg: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== prevState.counter) {
// some action here
}
}
Hooks Equivalent
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array
If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.
There are some subtleties to using useEffect; check out the API Here.
Before v16.7.0
The property of function components is that they don't have access to Reacts lifecycle functions or the this keyword. You need to extend the React.Component class if you want to use the lifecycle function.
class Grid extends React.Component {
constructor(props) {
super(props)
}
componentDidMount () {
if(!this.props.fetched) {
this.props.fetchRules();
}
console.log('mount it!');
}
render() {
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
}
Function components are useful when you only want to render your Component without the need of extra logic.
You can use react-pure-lifecycle to add lifecycle functions to functional components.
Example:
import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';
const methods = {
componentDidMount(props) {
console.log('I mounted! Here are my props: ', props);
}
};
const Channels = props => (
<h1>Hello</h1>
)
export default lifecycle(methods)(Channels);
You can make your own "lifecycle methods" using hooks for maximum nostalgia.
Utility functions:
import { useEffect, useRef } from "react";
export const useComponentDidMount = handler => {
return useEffect(() => handler(), []);
};
export const useComponentDidUpdate = (handler, deps) => {
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
return handler();
}, deps);
};
export const useComponentWillUnmount = handler => {
return useEffect(() => handler, []);
};
Usage:
import {
useComponentDidMount,
useComponentDidUpdate,
useComponentWillUnmount
} from "./utils";
export const MyComponent = ({ myProp }) => {
useComponentDidMount(() => {
console.log("Component did mount!");
});
useComponentDidUpdate(() => {
console.log("Component did update!");
});
useComponentDidUpdate(() => {
console.log("myProp did update!");
}, [myProp]);
useComponentWillUnmount(() => {
console.log("Component will unmount!");
});
return <div>Hello world</div>;
};
Solution One:
You can use new react HOOKS API. Currently in React v16.8.0
Hooks let you use more of React’s features without classes.
Hooks provide a more direct API to the React concepts you already know: props, state, context, refs, and lifecycle.
Hooks solves all the problems addressed with Recompose.
A Note from the Author of recompose (acdlite, Oct 25 2018):
Hi! I created Recompose about three years ago. About a year after
that, I joined the React team. Today, we announced a proposal for
Hooks. Hooks solves all the problems I attempted to address with
Recompose three years ago, and more on top of that. I will be
discontinuing active maintenance of this package (excluding perhaps
bugfixes or patches for compatibility with future React releases), and
recommending that people use Hooks instead. Your existing code with
Recompose will still work, just don't expect any new features.
Solution Two:
If you are using react version that does not support hooks, no worries, use recompose(A React utility belt for function components and higher-order components.) instead. You can use recompose for attaching lifecycle hooks, state, handlers etc to a function component.
Here’s a render-less component that attaches lifecycle methods via the lifecycle HOC (from recompose).
// taken from https://gist.github.com/tsnieman/056af4bb9e87748c514d#file-auth-js-L33
function RenderlessComponent() {
return null;
}
export default lifecycle({
componentDidMount() {
const { checkIfAuthed } = this.props;
// Do they have an active session? ("Remember me")
checkIfAuthed();
},
componentWillReceiveProps(nextProps) {
const {
loadUser,
} = this.props;
// Various 'indicators'..
const becameAuthed = (!(this.props.auth) && nextProps.auth);
const isCurrentUser = (this.props.currentUser !== null);
if (becameAuthed) {
loadUser(nextProps.auth.uid);
}
const shouldSetCurrentUser = (!isCurrentUser && nextProps.auth);
if (shouldSetCurrentUser) {
const currentUser = nextProps.users[nextProps.auth.uid];
if (currentUser) {
this.props.setCurrentUser({
'id': nextProps.auth.uid,
...currentUser,
});
}
}
}
})(RenderlessComponent);
componentDidMount
useEffect(()=>{
// code here
})
componentWillMount
useEffect(()=>{
return ()=>{
//code here
}
})
componentDidUpdate
useEffect(()=>{
//code here
// when userName state change it will call
},[userName])
According to the documentation:
import React, { useState, useEffect } from 'react'
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
});
see React documentation
Short and sweet answer
componentDidMount
useEffect(()=>{
// code here
})
componentWillUnmount
useEffect(()=>{
return ()=>{
//code here
}
})
componentDidUpdate
useEffect(()=>{
//code here
// when userName state change it will call
},[userName])
You can make use of create-react-class module.
Official documentation
Of course you must first install it
npm install create-react-class
Here is a working example
import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')
let Clock = createReactClass({
getInitialState:function(){
return {date:new Date()}
},
render:function(){
return (
<h1>{this.state.date.toLocaleTimeString()}</h1>
)
},
componentDidMount:function(){
this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
},
componentWillUnmount:function(){
clearInterval(this.timerId)
}
})
ReactDOM.render(
<Clock/>,
document.getElementById('root')
)
if you using react 16.8 you can use react Hooks...
React Hooks are functions that let you “hook into” React state and lifecycle features from function components...
docs
import React, { useState, useEffect } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
const [count2, setCount2] = useState(0);
// componentDidMount
useEffect(() => {
console.log("The use effect ran");
}, []);
// // componentDidUpdate
useEffect(() => {
console.log("The use effect ran");
}, [count, count2]);
// componentWillUnmount
useEffect(() => {
console.log("The use effect ran");
return () => {
console.log("the return is being ran");
};
}, []);
useEffect(() => {
console.log(`The count has updated to ${count}`);
return () => {
console.log(`we are in the cleanup - the count is ${count}`);
};
}, [count]);
return (
<div>
<h6> Counter </h6>
<p> current count: {count} </p>
<button onClick={() => setCount(count + 1)}>increment the count</button>
<button onClick={() => setCount2(count2 + 1)}>increment count 2</button>
</div>
);
};
export default Counter;

Categories