DEV Community

Keval Domadia
Keval Domadia

Posted on • Updated on

Understanding useEffect with useState easily

I have often been asked how to create a placeholder effect whilst the data is being fetched.

When you add a placeholder to the content, the user gets a feeling that the data is 'almost' loaded now.

I am writing this blog for my students to follow up incase they need a ready reference to check.

You need to 2 things. useState and useEffect

useEffect is a function that is used to manage side effects in your components. Side effects are things that your component needs to do that are not related to rendering content on the screen, such as fetching data from an API.

The best way to use useEffect() is in combination of useState().

Let me get down to the code to explain better. Check this out:

import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';

function MyComponent() {
  const [data, setData] = useState(false);

  useEffect(() => {
    fetch('https://example.com/api/getdata')
      .then(response => response.json())
      .then(data => setData(data));
  }, []);

  return (
    <View>
      {data ? <Text>{data}</Text> : <Text>Loading...</Text>}
    </View>
  );
}

Enter fullscreen mode Exit fullscreen mode

Now following this...

under View I have added a ternary operator to check if the data is true or false. By default it is false, thus the user will see loading...

When the useEffect reaches the second then, that is, processed json, it will set state of the data with the data from the API. This making it false-positive, or a True.

Alternatively, we can also create another state which changes and uses absolute True and False

To do that, check the code below:

import React, { useState, useEffect } from 'react';
import { Text, View } from 'react-native';

function MyComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('https://example.com/api/getdata')
      .then(response => response.json())
      .then(data => {
        setData(data);
        setLoading(false);
      });
  }, []);

  return (
    <View>
      {loading ? (
        <Text>Loading...</Text>
      ) : (
        <Text>{data}</Text>
      )}
    </View>
  );
}

Enter fullscreen mode Exit fullscreen mode

This puts loading as a boolean with either a true or a false, instead of false and true-y.

Hope this helps.

If you have more questions, you know where to reach me!

Be good. Get Good. Have fun!

Top comments (0)