Set a conditional initial value for useState in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# Set a conditional initial value for useState in React

To set a conditional initial value for useState in React:

  1. Pass a function to the useState hook.
  2. Use a condition to determine the correct initial value for the state variable.
  3. The function will only be invoked on the initial render.
App.js
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> ); }

set conditional initial value for usestate

The code for this article is available on GitHub

In the first example, we passed a function to the useState hook.

During the first render, the 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.

App.js
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.

App.js
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> ); }

using the ternary operator

The code for this article is available on GitHub

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.

App.js
const result1 = 5 === 5 ? 'yes' : 'no'; console.log(result1); // ๐Ÿ‘‰๏ธ "yes" const result2 = 5 === 10 ? 'yes' : 'no'; console.log(result2); // ๐Ÿ‘‰๏ธ "no"

how ternary operator works

The code for this article is available on GitHub

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev