So sometime I use setState inside an if statement to make sure it doesnt run unnecessarily. It works and I never get errors. I understand how sometimes useEffect can help in this situation from preventing extra re-renders but my question is, is useEffect always needed when using "useState" outside of the JSX? For example in a procedural sense like seen below when there is technically a falsy condition that prevents an infinite loops?
import { useEffect, useState } from "react";
import "./styles.css";
import Item from "./Item";
// EXAMPLE CODE TO HELP UNDERSTAND THE QUESTION MORE
export default function App() {
// I understand I do not need to check undefined as this is an example
const [state, setState] = useState();
if (state === undefined) {
setState([1, 2, 3, 4, 5]);
}
// vs
// useEffect(() => {
// if (state === undefined) {
// setState([1, 2, 3, 4, 5]);
// }
// }, [state]);
return <div className="App">{state}</div>;
}
CodePudding user response:
In this scenario the if condition is checked on every render outside of the useEffect.
With useEffect the if condition will only be checked if the state was modified for that render.
CodePudding user response:
Using the useState
inside useEffect
is not required since both hooks re-renders the component, using useState
in useEffect
would just re-render your component twice.
The if statement is okay.
const [state, setState] = useState();
sets state
to undefined
already - why check if the state is undefined? Its not required.
const [state, setState] = useState([1, 2, 3, 4, 5]);
For this case is okay.