user16602653
user16602653

Reputation:

Set state value depending on other states

I have some useState hooks which evaluate to true/false. Is there a way to have a string useState hook that updates its state to values depending on the most recent hook that evaluates to true?

An example situation might be:

stateA = false  
stateB = true  
set stringState = "B"  
stateA = true  
set stringState = "A"  

Upvotes: 1

Views: 100

Answers (1)

user16603402
user16603402

Reputation:

What you're probably looking for is React's useEffect hook.

For example, if you're using two variables, a and b, and want to update stringState to be "A" when a is true, "B" when b is true and a is false, and "C" when none is true, ie newStringState = a ? "A" : (b ? "B" : "C") (if a (is true) then "A", else if b (is true) then "B" else "C"), you can use the useEffect hook as follows:

const [a, setA] = React.useState(false)
const [b, setB] = React.useState(false)
const [stringState, setStringState] = React.useState("C")

React.useEffect(() => {
    // Code will run whenever a dependency (a or b) changes
    setStringState(a ? "A" : (b ? "B" : "C")
}, [a, b])

See this link for more details on the useEffect hook.

Depending on your implementation, you'll most likely not need stringState at all: you can directly put the condition in your components.

Upvotes: 1

Related Questions