All that React does with dependency arrays is check that the value at each index === the previous value at that index. Both null and undefined will return true if strictly compared against themselves, so having a null or undefined value as a dependency won't trigger the effect as long as it stays null or undefined. Note that null is not strictly equal to undefined or vice versa. So if you have a dependency that changes from null to undefined or vice versa, the effect will fire. Answer from landisdesign on reddit.com
🌐
Medium
medium.com › @o_o_o › null-vs-undefined-can-i-use-only-one-a3b7db5468f2
null vs. undefined: Can I use only one? | by OOO | Medium
March 29, 2022 - If you try to assign reference with value of undefined to an element’s ref, it throws a type error: But if you pass null as useRef’s initial value, the error goes away. ... When you are using useRef as a value container, you can change its value by modifying its .current property. Therefore its type is MutableRefObject<T>, and as its name states, you can mutate its .current value. When you are using useRef as an element reference, you can only read values from it and React itself is the only one allowed to do writes.
🌐
Bobby Hadz
bobbyhadz.com › blog › react-null-or-undefined-check
Check if a Variable is Null or Undefined in React | bobbyhadz
Copied!import {useEffect, useState} from 'react'; export default function App() { const [message, setMessage] = useState(undefined); useEffect(() => { // 👇️ Check if NOT undefined or null if (message !== undefined && message !== null) { console.log('✅ variable is NOT undefined or null'); } // 👇️ Check if undefined or null if (message === undefined || message === null) { console.log('✅ variable is undefined or null'); } else { console.log('⛔️ variable is NOT undefined or null'); } }, [message]); return ( <div> <button onClick={() => setMessage('Hello world')}>Set message</button> <h2>{message}</h2> </div> ); }
🌐
Saeloun Blog
blog.saeloun.com › 2022 › 04 › 14 › react-18-allows-components-to-render-undfined
React 18 allows components to render 'undefined' | Saeloun Blog
April 14, 2022 - Before React 18, if we did not want to render anything, we had to return 'null' or an empty fragment. React now allows undefined to be rendered.
🌐
Coding Beauty
codingbeautydev.com › home › posts › how to check if a variable is null or undefined in react
How to Check if a Variable is Null or Undefined in React
October 4, 2023 - To check if a variable in null or undefined in React, use the || operator to check if the variable is equal to null or equal to undefined.
🌐
GitHub
github.com › facebook › react › issues › 7204
Any reason to use "null" instead of "undefined" for default state? Using default would allow using es6 default values · Issue #7204 · facebook/react
July 6, 2016 - Not really an issue but... Any reason to use "null" instead of "undefined" for default state? Using default would allow using es6 default values
Published   Jul 06, 2016
Find elsewhere
🌐
GitHub
github.com › facebook › react › issues › 1647
React.PropTypes.renderable: `null` vs `undefined` · Issue #1647 · facebook/react
January 4, 2014 - evaluates to [undefined] which causes a warning. However, the following construct passes: isVisible = false [ if isVisible React.DOM.span {} else null ]
Published   Jun 05, 2014
🌐
CoreUI
coreui.io › blog › what-is-the-difference-between-null-and-undefined-in-javascript
What is the Difference Between Null and Undefined in JavaScript · CoreUI
February 9, 2025 - This article will walk you through the subtle difference between null and undefined, and offer best practices for handling them. Table of Contents · Angular · Bootstrap · React.js · Vue.js · In the original JavaScript implementation, undefined means a variable has been declared but has not been assigned a value.
🌐
Reddit
reddit.com › r/typescript › undefined vs null
r/typescript on Reddit: Undefined vs null
February 27, 2023 -

Since switching to TypeScript I have been using a lot of optional properties, for example:

type store = {
  currentUserId?: string
}

function logout () {
  store.currentUserId = undefined
}

However my coworkers and I have been discussing whether null is a more appropriate type instead of undefined, like this:

type store = {
  currentUserId: string | null
}

function logout () {
  store.currentUserId = null
}

It seems like the use of undefined in TypeScript differs slightly from in Javascript.

Do you guys/girls use undefined or null more often? And, which of the examples above do you think is better?

🌐
Reddit
reddit.com › r/reactjs › which is preferred among null, an empty fragment, and false?
r/reactjs on Reddit: Which is preferred among null, an empty Fragment, and false?
October 7, 2024 -

What is the appropriate approach in React when you don't want to render anything? I remember reading an article about a similar topic a few years ago, but I'm curious about the current state.

https://www.reddit.com/r/reactjs/comments/gtyr61/null_vs_empty_fragment/

It seems that the React documentation recommends using values like null, undefined, or false when you don't want to render anything. On the other hand, mentions of an empty Fragment are hard to find.

  • Fragment

  • Conditional Rendering

🌐
Jser
jser.dev › react › 2022 › 02 › 04 › how-React-handles-empty-values
How does React handle empty values(null/undfined/Booleans) internally?
In updateSlot() and updateFromMap(), we find the similar pattern in which empty values are simply ignored and null is returned. ... That’s it. We now know how empty values are handled in React - the are simply ignored.
🌐
Quora
quora.com › How-do-I-check-if-it-is-null-in-React-Native
How to check if it is null in React Native - Quora
Answer (1 of 2): Dude this is over my technological head, but I found this on the internet for you. Hope it makes sense to you because it’s Greek to me. Hope this helps. There are two options you can use. the && operator and If statement to check if the props exist.
Top answer
1 of 3
10

I think the best practice is to tell the user that your data is still loading, then populate the fields with the real data. This approach has been advocated in various blog-posts. Robin Wieruch has a great write up on how to fetch data, with a specific example on how to handle loading data and errors and I will go through his example here. This approach is generally done in two parts.

  1. Create an isLoading variable. This is a bolean. We initially set it to false, because nothing is loading, then set it to true when we try to fetch the data, and then back to false once the data is loaded.
  2. We have to tell React what to render given the two isLoading states.

1. Setting the isLoading variable

Since you did not provide any code, I'll just follow Wieruch's example.

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataFromApi: null,
    };
  }

  componentDidMount() {
    fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ dataFromApi: data.dataFromApi }));
  }

  ...
}

export default App;

Here we are using the browser's native fetch() api to get the data when the component mounts via the use of componentDidMount(). This should be quite similar to what you are doing now. Given that the fetch() method is asynchronous, the rest of the page will render and the state will be up dated once the data is received.

In order to tell the user that we are waiting for data to load, we simply add isLoading to our state. so the state becomes:

this.state = {
  dataFromApi: null,
  isLoading: false,
};

The state for isLoading is initially false because we haven't called fetch() yet. Right before we call fetch() inside componentDidMount() we set the state of isLoading to true, as such:

this.setState({ isLoading: true });

We then need to add a then() method to our fetch() Promise to set the state of isLoading to false, once the data has finished loading.

.then(data => this.setState({ dataFromAPi: data.dataFromApi, isLoading: false }));

The final code looks like this:

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      dataFromApi: [],
      isLoading: false,
    };
  }

  componentDidMount() {
    this.setState({ isLoading: true });

    fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ dataFromApi: data.dataFromApi, isLoading: false }));
  }

  ...
}

export default App;

2. Conditional Rendering

React allows for conditional rendering. We can use a simple if statement in our render() method to render the component based on the state of isLoading.

class App extends Component {
  ...

  render() {
    const { hits, isLoading } = this.state;

    if (isLoading) {
      return <p>Loading ...</p>;
    }

    return (
      <ul>
        {dataFromApi.map(data =>
          <li key={data.objectID}>
            <a href={data.url}>{data.title}</a>
          </li>
        )}
      </ul>
    );
  }
}

Hope this helps.

2 of 3
2

It Depends. suppose you are fetching books data from server. here is how to do that.

state = {
  books: null,
}

if, your backend api is correctly setup. You will get either empty array for no books or array with some length

componentDidMount(){
    getBooksFromServer().then(res => {
     this.setState({
     books: res.data
   })
  })
 }

Now In Your render method

   render() {
         const { books } = this.state;
         let renderData;
         if(!books) {
          renderData = <Spinner />
      } else
        if(books.length === 0) {
        renderData = <EmptyScreen />
       }
      else {
     renderData = <Books data = { books } />
   }
   
   return renderData;
   }  

If you are using offline data persistence In that case initially you won't have empty array.So This way of handling won't work. To show the spinner you have to keep a variable loader in state. and set it true before calling api and make it false when promise resolves or rejects.

finally read upon to state.

   const {loader} = this.state;
   if(loader) {
   renderData = <Spinner />
}