Friday, December 27, 2024

react useful links 11

  

  1. https://bigfrontend.dev/react 

  2. I collected all of the links in this post and wrote down bullet points for what I saw was repeatedly mentioned in the comments.

  3. I read every single page in the "Learn" section of the new React docs. This took two days as I was typing notes as I went along.

  4. Went through some practice problems and built a couple of user interfaces.I have yet to hear back about whether I'm being moved on to the next round but I thought I did pretty well. I was able to answer all of the questions I was asked about React and the coding portion was not difficult at all

In summary:

READ THE UPDATED REACT DOCUMENTATION (https://www.react.dev). It is very well written and the examples are great. I would not have been able to answer the majority of the questions in my interview if I had not read the docs. I'm not exaggerating even a little bit.In my opinion, if you're going for a mid level role, they're probably not going to ask you what state or props are, or what "lifting state up" means. Those are beginner questions that someone who has even 1 year of experience should already know.

  1. I would focus on knowing the major React Hooks. This was brought up repeatedly in the comments and the majority of my questions were based on Hooks.

- useState, useEffect, useRef, useReducer, useMemo, useCallback, useContext at the very minimum.

- When to use them, when not to use them.

- What does the second optional argument for useEffect do?

- What's the difference between useState and useRef?

- When would you use useState compared to useReducer?- What's the difference between useMemo and useCallback?

2. Custom Hooks - why you need them and how to write them.

- Examples: https://usehooks.com/

3. What can you do to improve the performance of your React application?- Know what the virtual DOM is and how React works in general- Memoization, lazy loading, dynamic imports, etc- Read this article

4. Something that the React docs mentioned over and over and that really stuck with me and changed my perspective on State and Hooks overall: learn when it's appropriate to use a Hook (useEffect in particular) and when to use an event handler.

Links I gathered from the comments (shout out to u/phiger78 for providing the majority of these):

- TypeScript tutorial - https://www.totaltypescript.com/tutorials

- Why booleans can be bad - https://kyleshevlin.com/enumerate-dont-booleanate

- React architecture - https://profy.dev/article/react-architecture-api-layer

- Using explicit States - https://www.youtube.com/watch?v=ul_3ABrpj64

- Frontend/React questions - https://greatfrontend.com/questions/react

- 100+ React questions - https://github.com/sudheerj/reactjs-interview-questions (some of these questions/answers haven't been updated for functional components so just be aware of that)



--------------


https://overreacted.io/a-complete-guide-to-useeffect/

Use this interview kit https://www.developerupdates.com/shop/front-end-developer-job-interview-kit

It covers most asked interview questions.






react links 10

 

  1. https://bigfrontend.dev/react 

  2. I collected all of the links in this post and wrote down bullet points for what I saw was repeatedly mentioned in the comments.

  3. I read every single page in the "Learn" section of the new React docs. This took two days as I was typing notes as I went along.

  4. Went through some practice problems and built a couple of user interfaces.I have yet to hear back about whether I'm being moved on to the next round but I thought I did pretty well. I was able to answer all of the questions I was asked about React and the coding portion was not difficult at all

In summary:

READ THE UPDATED REACT DOCUMENTATION (https://www.react.dev). It is very well written and the examples are great. I would not have been able to answer the majority of the questions in my interview if I had not read the docs. I'm not exaggerating even a little bit.In my opinion, if you're going for a mid level role, they're probably not going to ask you what state or props are, or what "lifting state up" means. Those are beginner questions that someone who has even 1 year of experience should already know.

  1. I would focus on knowing the major React Hooks. This was brought up repeatedly in the comments and the majority of my questions were based on Hooks.

- useState, useEffect, useRef, useReducer, useMemo, useCallback, useContext at the very minimum.

- When to use them, when not to use them.

- What does the second optional argument for useEffect do?

- What's the difference between useState and useRef?

- When would you use useState compared to useReducer?- What's the difference between useMemo and useCallback?

2. Custom Hooks - why you need them and how to write them.

- Examples: https://usehooks.com/

3. What can you do to improve the performance of your React application?- Know what the virtual DOM is and how React works in general- Memoization, lazy loading, dynamic imports, etc- Read this article

4. Something that the React docs mentioned over and over and that really stuck with me and changed my perspective on State and Hooks overall: learn when it's appropriate to use a Hook (useEffect in particular) and when to use an event handler.

Links I gathered from the comments (shout out to u/phiger78 for providing the majority of these):

- TypeScript tutorial - https://www.totaltypescript.com/tutorials

- Why booleans can be bad - https://kyleshevlin.com/enumerate-dont-booleanate

- React architecture - https://profy.dev/article/react-architecture-api-layer

- Using explicit States - https://www.youtube.com/watch?v=ul_3ABrpj64

- Frontend/React questions - https://greatfrontend.com/questions/react

- 100+ React questions - https://github.com/sudheerj/reactjs-interview-questions (some of these questions/answers haven't been updated for functional components so just be aware of that)



--------------


https://overreacted.io/a-complete-guide-to-useeffect/

Use this interview kit https://www.developerupdates.com/shop/front-end-developer-job-interview-kit

It covers most asked interview questions.







ERRORBOUNDRY--Fetching data using a custom hook-AND LifecycleHooks

Summary

  • componentDidMount: Called after the component is mounted. Ideal for fetching data or setting up subscriptions.

  • componentDidUpdate: Called after the component is updated. Useful for responding to changes in props or state.

  • componentWillUnmount: Called right before the component is unmounted. Perfect for cleanup tasks.

These lifecycle methods provide powerful hooks for managing the behavior of your components at different points in their lifecycle.


Certainly! React lifecycle methods can be categorized into three main phases: Mounting, Updating, and Unmounting. Here's a comprehensive overview of each phase and the associated lifecycle methods 



1.Example Implementation in Class Components-RightSide 

Functional Component Alternatives

In functional components, React hooks like useEffect and useState can be used to achieve similar lifecycle behaviors.


Summary

  • Mounting: constructor, getDerivedStateFromProps, render, componentDidMount

  • Updating: getDerivedStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, componentDidUpdate

  • Unmounting: componentWillUnmount

Functional component hooks provide a more concise and readable way to manage component lifecycle in modern React applications.

________________________________________________________________


ERRORBOUNDARY:

useGet/useFetch or give any name for custom hook creating 
Sure! Let's create clear and concise code for fetching data using a custom hook, with appropriate component names. 

The useFetch function in React is typically a custom hook used for fetching data from an API. It abstracts the data fetching logic, making it reusable and clean. I'll show you how to create a simple useFetch hook using the react-query library.

Step 1: Install React Query

First, you'll need to install react-query if you haven't already:

bash
npm install react-query

Step 2: Create the useFetch Hook

Here's a simple implementation of useFetch using react-query:

### Step 1: Create the Custom Hook
Create a file called `useFetch.js`:

import { useQuery } from 'react-query';

const useFetch = (url) => {
  return useQuery(['fetchData', url], async () => {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  });
};

export default useFetch;

### Step 2: Create the ErrorBoundary Component
Create a file called `ErrorBoundary.js`:

 import React, { Component } from 'react';
class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("ErrorBoundary caught an error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

### Step 3: Create the DataFetchingComponent
Create a file called `DataFetchingComponent.js`:

import React from 'react';
import useFetch from './useFetch';

const DataFetchingComponent = () => {
  const { data, error, isLoading } = useFetch('https://api.example.com/data');

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>Data:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export default DataFetchingComponent;

### Step 4: Use the ErrorBoundary in the App Component
Create a file called `App.js`:

 import React from 'react';
import ErrorBoundary from './ErrorBoundary';
import DataFetchingComponent from './DataFetchingComponent';

const App = () => {
  return (
    <ErrorBoundary>
      <DataFetchingComponent />
    </ErrorBoundary>
  );
};

export default App;

### Explanation

  1. Custom Hook (useFetch):
  • Fetches data from the given URL.
  • Uses react-query to handle data fetching, caching, and synchronization.
  1. ErrorBoundary Component:
  • Catches errors in its child components.
  • Displays a fallback UI (Something went wrong) if an error occurs.
  1. DataFetchingComponent:
  • Uses the useFetch hook to fetch data.
  • Renders loading state, error state, or the fetched data.
  1. App Component:
  • Wraps DataFetchingComponent with ErrorBoundary to catch and handle any errors that occur during data fetching.

This setup provides a clear and reusable way to handle data fetching with error boundaries in a React application. If you have any more questions or need further assistance, feel free to ask!

Saturday, November 18, 2023

Input component for reuse

 


import React from 'react'
import classes from './Input.module.css'

const Input = (props) => {
  return (
    <div className={classes.input}>
        <label htmlFor={props.input.id}>{props.label}</label>
        <input {...props.input}/>

    </div>
  )
}

export default Input
  1. Passing from below from another component where input requireed <Input
  2. label='Amount'
  3. input={{
  4. id: 'amount',
  5. type: 'number',
  6. min: '1',
  7. max: '5',
  8. step: '1',
  9. defaultValue: '1',
  10. }}
  11. />


in
in


Sunday, October 22, 2023

React reducer dispatch increment decrement button

dispatching in 2 ways 1.directly and 2 with function
++++++++++


import { useReducer,React } from 'react';
import './App.css';

const incReducer=(state,action)=>{
 
  if(action.type==="dec"){
    return {"val":state.val-1};
  }if(action.type==="inc"){
    return {"val":state.val+1};
  }
}
function App() {
  const [state,dispatch]=useReducer(incReducer,{"val":0});
const ipchangeHandler=(ty)=>{
 dispatch({"type":ty})
}

  return (
    <div>
      <button type='button' onClick={(event)=>ipchangeHandler('dec',event.target.value)}>Decrement</button>
      {state.val}
      <button type='button' onClick={()=>dispatch({"type":"inc"})}>Increment</button>
    </div>
  );
}

export default App;

=====================================
type 1 passing dispatch

   <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
    </div>


type 2 passing dispatch through function

   <div>
      <button type='button' onClick={(event)=>ipchangeHandler('dec',event.target.value)}>Decrement</button>
      {state.val}
      <button type='button' onClick={(event)=>ipchangeHandler('inc',event.target.value)}>Increment</button>
    </div>


  const [state,dispatch]=useReducer(incReducer,{"val":0});
const ipchangeHandler=(ty)=>{
 dispatch({"type":ty})
}



const incReducer=(state,action)=>{
 
  if(action.type==="dec"){
    return {"val":state.val-1};
  }if(action.type==="inc"){
    return {"val":state.val+1};
  }
}





 

Tuesday, December 13, 2022

React: UseEffect Dec

 const Login = (props) => {

  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState();
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  useEffect(()=>{
   const identifier= setTimeout(()=>{
    console.log('triggered only once for all the  keystrokes typed in between 1000millis')
    setFormIsValid(
      enteredEmail.includes('@') && enteredPassword.trim().length > 6
    );
   },1000);
   return ()=>{
    console.log("cleanup...")
    clearTimeout(identifier);
  };  //cleaning up after 5seconds
  },[enteredEmail, enteredPassword])
  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);

    // setFormIsValid( // moved to useEffect.
    //   event.target.value.includes('@') && enteredPassword.trim().length > 6
    // );
  };
const passwordChangeHandler = (event) => {
    setEnteredPassword(event.target.value);

    setFormIsValid(
      event.target.value.trim().length > 6 && enteredEmail.includes('@')
    );
  };
 const validateEmailHandler = () => {
    setEmailIsValid(enteredEmail.includes('@'));
  };

  const validatePasswordHandler = () => {
    setPasswordIsValid(enteredPassword.trim().length > 6);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(enteredEmail, enteredPassword);
  };




  <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            emailIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={enteredEmail} placeholder="UseEffect Used Here-- [Check Console]"
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${
            passwordIsValid === false ? classes.invalid : ''
          }`}
        >


FILE: LOGIN.js
import React, { useEffect, useState } from 'react';

import Card from '../UI/Card/Card';
import classes from './Login.module.css';
import Button from '../UI/Button/Button';

const Login = (props) => {
  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState();
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  useEffect(()=>{
   const identifier= setTimeout(()=>{
    console.log('triggered only once for all the  keystrokes typed in between 1000millis')
    setFormIsValid(
      enteredEmail.includes('@') && enteredPassword.trim().length > 6
    );
   },1000);
   return ()=>{
    console.log("cleanup...")
    clearTimeout(identifier);
  };  //cleaning up after 5seconds
  },[enteredEmail, enteredPassword])
  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);

    // setFormIsValid( // moved to useEffect.
    //   event.target.value.includes('@') && enteredPassword.trim().length > 6
    // );
  };

  const passwordChangeHandler = (event) => {
    setEnteredPassword(event.target.value);

    setFormIsValid(
      event.target.value.trim().length > 6 && enteredEmail.includes('@')
    );
  };

  const validateEmailHandler = () => {
    setEmailIsValid(enteredEmail.includes('@'));
  };

  const validatePasswordHandler = () => {
    setPasswordIsValid(enteredPassword.trim().length > 6);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(enteredEmail, enteredPassword);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            emailIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={enteredEmail} placeholder="UseEffect Used Here-- [Check Console]"
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${
            passwordIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            value={enteredPassword}
            onChange={passwordChangeHandler}
            onBlur={validatePasswordHandler}
          />
        </div>
        <div className={classes.actions}>
          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>
        </div>
      </form>
    </Card>
  );
};

export default Login;