Home > Software design >  What type of value gets passed to setState function?
What type of value gets passed to setState function?

Time:10-16

I saw a React training video with the following code:

const [darkTheme, setDarkTheme] = useState(true)
  
function toggleTheme() { 
    setDarkTheme(prevDarkTheme => !prevDarkTheme)
}

In the last line, what is being passed as a parameter to the setDarkTheme function? I thought a function needs a single value so can't tell if that is an arrow function that is evaluated before passing it, or what.

CodePudding user response:

setDarkTheme(prevDarkTheme => !prevDarkTheme)

prevDarkTheme here is actual value of this state. We should use function here when there can be a possibility that something else can change this state in meantime. By using prevDarkTheme you are always sure that it is the latest value. You can read more about it here

CodePudding user response:

setState accepts either a value or a function

and when it gets a function that function will be called with the previous state

and note that it's very recommended to always pass a function to make sure you are changing the state correctly

DONT DO

    setDarkTheme(!prevDarkTheme)

DO

    setDarkTheme(prevDarkTheme => !prevDarkTheme)

CodePudding user response:

its the current value in state variable. in this case it will be true

function toggleTheme() { 
    setDarkTheme((prevDarkTheme /* true */ ) => !prevDarkTheme /* !true -> false*/) // false
}
  • Related