Saturday, January 6, 2024

Day 24 || useState in React || useEffect in React || React hooks

React.js Topics

Day 24:

  • React Hooks
    • useState()
    • useEffect()

useState():

  Playground.js

import { useState } from "react";
import "./Playground.css";
const Playground = () => {
  const [gameScore, setGameScore] = useState(0);
  const [artistName, setArtistName] = useState("Mahesh")
  const handleIncrement = () => {
    setGameScore(gameScore + 1);
  };
  const handleDecrement = () => {
    if (gameScore > 0) {
      setGameScore(gameScore - 1);
    }
  };
  const handleChangeName = (e)=>{
    setArtistName(e.target.value)
  }
  return (
    <div className="playground-container">
      <h1>Playground : Art Competition</h1>
      <h3>Artist Name: <span> {artistName}</span></h3>
      <h3>Game Score: <span>{gameScore}</span></h3>
      <div>
        <input type="text" onChange={handleChangeName}/>
        <button onClick={handleIncrement}>Increase Score</button>
        <button onClick={handleDecrement}>Decrease Score</button>
      </div>
    </div>
  );
};
export default Playground;


  Playground.css

.playground-container {
  background: url("https://images.unsplash.com/photo-1604921827342-b4bc94df162c?q=80&w=1933&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D");
  background-size: 100% 100%;
  height: 100vh;
  text-align: center;
  border-radius: 5px;
  margin: 10px;
}
.playground-container span{
    color: red;
}
.playground-container input{
    padding: 10px;
    border-radius: 5px;
    border: none;
}
.playground-container button {
    padding: 10px;
    background-color: rgb(104, 119, 219);
    color: white;
    border-radius: 5px;
    border: none;
    margin: 5px;
}


useEffect():

DataFetchingApi.js

import { useEffect, useState } from "react";
const DataFetchingApi = () => {
  const [data, setData] = useState([]);
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => {
        return response.json();
      })
      .then((json) => {
        console.log(json);
        return setData(json);
      });
  }, []);

  return (
    <div>
      Data Fetching Api
      <div>{data.map((item)=>{
        console.log(item.title);
       return(<li>{item.title}</li>)
      })}</div>
    </div>
  );
};
export default DataFetchingApi;


Interview Questions:

1. What is a React Hook?

2. What is the purpose of the second element returned by useState?

3. How do you update state in a functional component?

4. Explain the purpose of the dependency array in useEffect?

5. What are common use cases for useEffect?


No comments:

Post a Comment

Top 10 | JavaScript Coding Interview Question | Beginner Level

               JavaScript Coding Interview  Q. No. 01/10:  console . log ( "1" + "4" + "1" ) // 141 console . ...