简体   繁体   中英

When using the useState hook outside of JSX do I have to wrap it inside useEffect everytime?

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>;
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM