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;
useEffect
is a React hook, lets you perform side effects in function components.As per your sample code, this
useEffect
will run wheneverresourcetype
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 ofuseEffect
if your function returns another function, that function will execute when your component unmounts.Here is some information about the
useEffect
hook: https://reactjs.org/docs/hooks-effect.htmlEssentially
useEffect
acts ascomponentDidMount
,componentDidUpdate
, andcomponentWillUnmount
. Those function are called by React during different parts of the component lifecycle, and do not need areturn
statement to work, as you can call functions withoutreturn
statements similarly as you call functions withreturn
statements.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