5

I have a function named getAllEmployees which I export from another file.

const getAllEmployees = () => {
    return [1,2,3,4,5,6,7,8,9]
}

export { getAllEmployees }

now I use React.useState(getAllEmployees). this gives me the result, when I call like React.useState(getAllEmployees()) it also gives me same result, event when call like React.useState(() => getAllEmployees()) this also gives me the same result.

import here

import { getAllEmployees } from './Service/Service'

use with useState

const [result] = useState(getAllEmployees ) or
const [result] = useState(getAllEmployees()) or
const [result] = useState(() => getAllEmployees())

console.log(result)

for all of those result is

 (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]

My question is why they gives me same results, and which is the right way?

A.S.Abir
  • 93
  • 7
  • 3
    const [result, setResult] = useState(getAllEmployees); –  Feb 17 '21 at 08:45
  • here I am not interested to set result again. for that just get the value from the function, that's why I use [result] only – A.S.Abir Feb 17 '21 at 09:22

1 Answers1

6

Why they gives me same results?

  1. const [result] = useState(getAllEmployees)

    React useState hook can take a lazy initializer function, to be invoked when the component is mounting and state is being initialized. You are passing a callback for React to call and initialize state with the return value.

  2. const [result] = useState(getAllEmployees())

    This is simply immediately invoking the function and passing the return value to the hook to be the initial state. Note that this function will be called each render cycle and the result only used from the initial render, all subsequent calls will be ignored. If the function is "heavy" it can adversely affect performance since it is needlessly called.

  3. const [result] = useState(() => getAllEmployees())

    This is the same as 1, but you've passed an anonymous initializing function.

Which is the right way?

The right way is the one that works for your use case, is easy to read and understand, and maintain. 1 and 3 are correct and functionally equivalent, though 3 is a bit redundant/unnecessary. 2 should be avoided. As noted above this function will be called each time the component renders and since the initial state value passed to useState is ignored on all subsequent renders 2 is just doing a lot of unnecessary work for no reason.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181