Some Important concepts while using React #Learnings-1

Subscribe to my newsletter and never miss my upcoming articles

Using useEffect for fetching api response:-

useEffect(()=>{
    fetch(`https://pixabay.com/api/?key=${process.env.REACT_APP_PIXABAY_API_KEY}&q=${term}&image_type=photo`)
    .then(res => res.json())
    .then(data => 
      {
        setImages(data.hits); 
        setIsLoading(false);
      }
    )
    .catch(err => console.log(err));
  });
  • Generalized Syntax of UseEffect
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
} 
// credits:- devhints.io

Using map to iterate over arrays or any iterables:-

<div className="container mx-auto">
      <div className="grid grid-cols-3 gap-4">
        {images.map(image => (
          <ImageCard key={image.id} image={image}/>
        ))}
      </div>
</div>
  • Generalized Syntax of map
array.map(i=>(
   // do some operation with i
))

Using Ternary Operators in Rendering Components

What we say as Conditional Rendering

{
isLoading? <h1 className = "text-6xl text-center mx-auto mt-32">Loading...</h1> : <div className="grid grid-cols-3 gap-4">
        {images.map(image => (
          <ImageCard key={image.id} image={image}/>
        ))}
</div>
}
  • Generalized syntax of ternary operators:-
/*true*/  ? /*do this*/ : /*else this*/

Passing Props from one component to another:-

<ImageSearch searchText = {(text) => setTerm(text)}/>

No Comments Yet