Check if Variable is Null in React

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Check out my new book

Check if Variable is Null in React #

To check for null in React, use a comparison to check if the value is equal or is not equal to null, e.g. if (myValue === null) {} or if (myValue !== null) {}. If the condition is met, the if block will run.

App.js
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(null); useEffect(() => { // ✅ Check if NOT equal to null if (message !== null) { console.log('variable is NOT null'); } // ✅ Check if null if (message === null) { console.log('variable is null'); } // ✅ Check if value is NOT equal to null and undefined if (message !== undefined && message !== null) { console.log('variable is NOT undefined or null'); } // ✅ Check if value is equal to null or undefined if (message === undefined || message === null) { console.log('variable is undefined or null'); } }, [message]); return ( <div> <button onClick={() => setMessage('Hello world')}>Set message</button> <h2>{message}</h2> </div> ); }

If our first if statement, we check if the message variable is not equal to null.

The second example checks if the variable is equal to null.

The third if statement checks if the variable is not equal to undefined and not equal to null.

The fourth example checks if the variable is equal to undefined or equal to null.

We used the useEffect hook to track changes to the message state variable, however you can perform the check anywhere in your code.

You can also check if a variable stores a truthy value.

The truthy values are all values that are not falsy.

The falsy values in JavaScript are: undefined, null, false, 0, "" (empty string), NaN (not a number).

App.js
import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(null); useEffect(() => { if (message) { console.log('✅ variable is truthy'); } if (!message) { console.log('⛔️ variable is falsy'); } }, [message]); return ( <div> <button onClick={() => setMessage('Hello world')}>Set message</button> <h2>{message}</h2> </div> ); }

The first condition checks if the message variable stores a truthy value.

The variable could store any value other than the 7 falsy values for the condition to be met.

The second if statement checks if the variable stores one of the 7 falsy values - undefined, null, false, 0, "" (empty string), NaN (not a number).

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