Set a conditional initial value for useState in React

avatar

Borislav Hadzhiev

Fri Apr 22 20222 min read

banner

Photo by Ben Eaton

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> ); }

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, you can use a 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> ); }

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"

If the string hi has a length of 2 characters, we return hello world as the initial state value, otherwise test is returned.

Use the search field on my Home Page to filter through my more than 1,000 articles.