Home > Blockchain >  React Log Running Twice
React Log Running Twice

Time:10-04

I'm new to React and was wondering why console.log() was executing twice when I run my app?

import React, { useState } from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
import SearchBar from '../components/SearchBar';
import useResults from '../hooks/useResults';
import ResultsList from '../components/ResultsList';

const SearchScreen = () => {
    const [ term, setTerm ] = useState( '' ),
        [ searchApi, results, errorMessage ] = useResults();

    const filterResultsByPrice = ( price ) => {
        return results.filter( result => {
            return result.price === price;
        } );
    }

    console.log( results[0].name ); // Is being printed twice. Why?

    return (
        <View style={ { flex: 1 } }>
            <SearchBar
                term={ term }
                onTermChange={ setTerm }
                onTermSubmit={ () => searchApi( term ) }
            />
            { errorMessage ? <Text>{ errorMessage }</Text> : null }
            <Text>We have found { results.length } results.</Text>
            <ScrollView>
                <ResultsList title="Cost Effective" results={ filterResultsByPrice( '$' ) } />
                <ResultsList title="Bit Pricier" results={ filterResultsByPrice( '$$' ) } />
                <ResultsList title="Big Spender" results={ filterResultsByPrice( '$$$' ) } />
                <ResultsList title="Price Unknown" results={ filterResultsByPrice( undefined ) } />
            </ScrollView>
        </View>
    );
};

const styles = StyleSheet.create( {} );

export default SearchScreen;

When I view the log in Git Bash, I notice it's executed twice instead of just once, why is that?

CodePudding user response:

Because your component re-renders twice:

  1. when the state is initialized
  2. when the state is updated.

Therefore your code in the component body re-executes so to say.

CodePudding user response:

It is expected behavior as components can render several times. The console log is just getting executed whenever your component renders.

To execute some code only once (When the component is mounted for the first time), use useEffect hook passing the second parameter as [ ] (an empty array).

Or perhaps, you might want to print to console whenever the results change. So instead of an empty array, you can pass [results] as the second param to useEffect so that the code within useEffect gets executed whenever the results change and not on every render.

useEffect(() => {
    console.log(results[0].name);
}, [results]);

Here is a good explanation if you are new to useEffect hook: useEffect

  • Related