Search code examples
reactjsrxjsuse-statereact-stateconditional-rendering

How to add if condition inside of useState in React


I want to add if condition inside of use state. So here is my code example:

const [buttonName, setButtonName] = useState('Connect Wallet');

  const changeButtonName = () => {
    localStorage.getItem('address') ? setButtonName('Wallet Connected') : setButtonName('Connect Wallet');
  };

so I want to add changeButtonName into useState. The reason why I want to do it is as soon as the page renders I want to check if there is address in local and if there is I want to set the name of the button.

Thanks


Solution

  • you can initialize state lazily

    const [buttonName, setButtonName] = useState(() => {
        return localStorage.getItem('address') ? 'Wallet Connected' : 'Connect Wallet'
      });