2

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")

  
  useEffect(()=>{
    console.log("render")
  },[resourcetype])
  
  return (
    <div>
      <button onClick={()=>setresourcetype("try")}>try</button>
      <button onClick={()=>setresourcetype("unknown")}>unknown</button>
    </div>
  );
}

export default App;

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Yan Skywalker
  • 119
  • 1
  • 10

3 Answers3

1

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

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • You mean it's not necessary to add return when using block in arrow function?And without return arrow function with block will still return a value which is undefined? – Yan Skywalker Feb 20 '21 at 05:18
0

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.

Aarni Joensuu
  • 711
  • 8
  • 19
0

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

 useEffect(()=>{
    console.log("render")
  },[resourcetype])

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.

 useEffect(()=>{
    console.log("Mounted")
    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.

Jaskaran Singh
  • 2,392
  • 24
  • 39