Why in the following code useEffect hook uses the curly braces, but without return statement, it still works?

after I read this article When should I use a return statement in ES6 arrow functions, I’m still a little bit confused.Why the following code useEffect uses the curly braces, but without return it still works? Not sure if I misunderstand something.
Here is the example:

import React,{useEffect,useState} from "react"

function App() {
  const [resourcetype,setresourcetype]=useState("posts")

  return (
      <button onClick={()=>setresourcetype("try")}>try</button>
      <button onClick={()=>setresourcetype("unknown")}>unknown</button>

export default App;

3 thoughts on “Why in the following code useEffect hook uses the curly braces, but without return statement, it still works?”

  1. useEffect is a React hook, lets you perform side effects in function components.
    As per your sample code, this useEffect will run whenever resourcetype variable will change.
    As per the documentation of useEffect it accepts a function as an argument and executes that function.
    As per your sample code


    the function you have passed to useEffect is not returning anything, as per the documentation of useEffect if your function returns another function, that function will execute when your component unmounts.

        return () => { console.log("component unmounted")}

    Bottom line is we don’t want/need to return any value (string, number
    etc) from the function that we are passing to useEffect hook.

  2. Here is some information about the useEffect hook: https://reactjs.org/docs/hooks-effect.html

    Essentially useEffect acts as componentDidMount, componentDidUpdate, and componentWillUnmount. Those function are called by React during different parts of the component lifecycle, and do not need a return statement to work, as you can call functions without return statements similarly as you call functions with return statements.

  3. Like a function declaration or expression, the return statement for an arrow function with a block is optional. If you omit it then the function returns undefined


Leave a Comment