Reputation: 5071
Why and when should I useEffect if I have no deps?
What is the difference between (from React docs):
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
And without useEffect?
function usePrevious(value) {
const ref = useRef();
ref.current = value;
return ref.current;
}
Upvotes: 1
Views: 469
Reputation: 281626
The difference in the two methods is that useEffect
is run after the render cycle is complete and hence ref.current will hold the previous values whereas in the second method, your ref.current will be updated immediately and hence the previous will always be equal to the current value
Sample demo
const {useRef, useEffect, useState} = React;
function usePreviousWithEffect(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
function usePrevious(value) {
const ref = useRef();
ref.current = value;
return ref.current;
}
const App = () => {
const [count, setCount] = useState(0);
const previousWithEffect = usePreviousWithEffect(count);
const previous = usePrevious(count);
return (
<div>
<div>Count: {count}</div>
<div>Prev Count with Effect: {previousWithEffect}</div>
<div>Prev Count without Effect: {previous}</div>
<button type="button" onClick={() => setCount(count => count + 1)}>Increment</button>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>
Also to answer your question, you pass useEffect
without dependency when you want to perform some operation on each render. You however cannot set state or perform an action that will cause a re-render otherwise your app will go in a loop
Upvotes: 1