Set a conditional initial value for useState in React

Set a conditional initial value for useState in React

This article will show you how to set a conditional initial value for useState in React by using the conditional operator or calling a function method. Read this article now to get more knowledge.

How to set a conditional initial value for useState in React

Using the ternary operator

Javascript ternary is like Javascript if else condition. Ternary operator helps programmers can quickly check a condition in Javascript. Javascript ternary is used to shorten the statement when checking a condition. This is useful for returning a value (assigning it to another variable). This way, we can write concise code right in the setState function. 

Code:

import React, { useState } from "react";
const App = () => {
  const condition = 1;
  const [message] = useState(condition === 1 ? "true" : "false");
  return (
    <>
      <h2>
        Set a conditional initial value for useState in React | LearnShareIT
      </h2>
      <hr />
      <h3>{message}</h3>
    </>
  );
};
 
export default App;

Output:

As you can see in the above code, we will use a condition variable to pass the ternary operator. When this variable is equal to 1, it will return “true”; otherwise, return “false” to setState for the state message. So with the condition variable equal to one, we return the value “true” and render to the screen, or you can also refer to the method below.

Calling a function method

In this function, we will use the if else condition pair to return a conditional initial value for the setState function to set this value for the state. This function will be called inside useState(), and it will run with a passed parameter, which is the condition variable we have defined.

Code:

import React, { useState } from "react";
const App = () => {
  const condition = 1;
  const returnState = (condition) => {
    if (condition === 1) {
      return "true";
    } else {
      return "false";
    }
  };
  const [message] = useState(returnState(condition));
  return (
    <>
      <h2>
        Set a conditional initial value for useState in React | LearnShareIT
      </h2>
      <hr />
      <h3>{message}</h3>
    </>
  );
};

export default App;

In this way, we will use a defined function to return the value according to the condition we need to consider. This function takes a condition value to test and returns different values ​​under different conditions. So we can set a conditional initial value for useState in React. Good luck with the above methods.

Summary

To summarize, you already know how to set a conditional initial value for useState in React. But you should learn and use the ternary operator method because this method is very concise and easy to understand. Good lucks!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *