STOP ! useEffect
is in an infinite loop
Each time you setPos(...)
, the component re-renders and calls useEffect()
again . You want to avoid that, hence you will have to pass in a secondary argument of []
, to make it behave like componentDidMount
which basically stop the useEffect
effect from firing more than once. Coz now it depends on no elements i.e []
const [pos, setPos] = useState(null);
useEffect(()=>{
if(someCondition){setPos('left')}
else{setPos('right')}
}, []);
return (
<div style={{ [pos] : 0 }} />
)
The infinite loop of changing pos
was stopping your component from rendering properly.
Link : https://reactjs.org/docs/hooks-effect.html
(See the note at the end of the page)
Note
If you use this optimization, make sure the array includes all values
from the component scope (such as props and state) that change over
time and that are used by the effect. Otherwise, your code will
reference stale values from previous renders. Learn more about how to
deal with functions and what to do when the array changes too often.
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. This isn’t handled as a special
case — it follows directly from how the dependencies array always
works.
If you pass an empty array ([]), the props and state inside the effect
will always have their initial values. While passing [] as the second
argument is closer to the familiar componentDidMount and
componentWillUnmount mental model, there are usually better solutions
to avoid re-running effects too often. Also, don’t forget that React
defers running useEffect until after the browser has painted, so doing
extra work is less of a problem.