Last updated: Apr 6, 2024
Reading timeยท2 min
To set a conditional initial value for useState in React:
useState
hook.import {useState} from 'react'; export default function App() { // ๐๏ธ Passing function to useState const [num, setNum] = useState(() => { if (2 * 2 === 4) { return 4; } return 42; }); // ๐๏ธ Using a ternary const [str, setStr] = useState('hi'.length === 2 ? 'hello world' : 'test'); return ( <div> <h2>num is: {num}</h2> <h2>str is: {str}</h2> </div> ); }
In the first example, we passed a function to the useState hook.
num
variable is going to store whatever we returned from the callback function we passed to useState
.We can use conditionals in the function in order to determine the correct value for the state variable.
Passing a function to the useState
method is useful when the initial state is
the result of an expensive computation.
The function we passed to useState
will only be invoked on the initial render.
const [state, setState] = useState(() => { const initialState = someExpensiveComputation(props); return initialState; });
This pattern is called lazy initial state.
If you need a quick, one-liner conditional to determine the initial state value, use the ternary operator.
import {useState} from 'react'; export default function App() { // ๐๏ธ Using a ternary const [str, setStr] = useState('hi'.length === 2 ? 'hello world' : 'test'); return ( <div> <h2>str is: {str}</h2> </div> ); }
The ternary operator is very similar to an if/else
statement.
If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.
const result1 = 5 === 5 ? 'yes' : 'no'; console.log(result1); // ๐๏ธ "yes" const result2 = 5 === 10 ? 'yes' : 'no'; console.log(result2); // ๐๏ธ "no"
If the string hi
has a length of 2
characters, we return hello world
as
the initial state value, otherwise test
is returned.
You can imagine that the value before the colon is the if
block and the value
after the colon is the else
block.
Make sure you don't call hooks conditionally when using React.
I've also written an article on how to set a default value for an input field.