React Advanced - Class 3

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 61 :- React Advanced - Class 3

In "React Advanced - Class 3," we'll continue exploring more advanced React concepts and build on what we learned in the previous classes. We'll cover topics such as React context, error boundaries, and advanced hooks like useReducer and useRef.

Step 1: React Context

React Context provides a way to pass data through the component tree without having to pass props down manually at every level. It allows you to create a global state accessible to all components within a specific context.

Creating a Context:

jsxCopy code

// ThemeContext.js import { createContext, useState } from 'react'; const ThemeContext = createContext(); export const ThemeProvider = ({ children }) => {  const [theme, setTheme] = useState('light');  return (    <ThemeContext.Provider value={{ theme, setTheme }}>      {children}    </ThemeContext.Provider>  ); }; export default ThemeContext;

In this example, we created a ThemeContext using createContext and provided a ThemeProvider component that wraps its children with the ThemeContext.Provider. It holds the theme state and the setTheme function as the value of the context.

Using the Context:

jsxCopy code

// App.js import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import { ThemeProvider } from './ThemeContext'; import Home from './Home'; import About from './About'; import Products from './Products'; function App() {  return (    <Router>      <ThemeProvider>        <div>          <h1>Hello, React!</h1>          <nav>            <ul>              <li>                <Link to="/">Home</Link>              </li>              <li>                <Link to="/about">About</Link>              </li>              <li>                <Link to="/products">Products</Link>              </li>            </ul>          </nav>          <Route exact path="/" component={Home} />          <Route path="/about" component={About} />          <Route path="/products" component={Products} />        </div>      </ThemeProvider>    </Router>  ); } export default App;

In this example, we wrapped the entire application with the ThemeProvider to make the theme state and setTheme function accessible to all child components.

Step 2: Error Boundaries

Error boundaries are components that catch JavaScript errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. They help prevent the entire application from crashing due to errors in specific components.

jsxCopy code

// ErrorBoundary.js import React, { Component } from 'react'; class ErrorBoundary extends Component {  state = {    hasError: false,  };  static getDerivedStateFromError(error) {    return { hasError: true };  }  componentDidCatch(error, errorInfo) {    // You can log the error to an error reporting service    console.error('Error:', error);    console.error('Error Info:', errorInfo);  }  render() {    if (this.state.hasError) {      return <div>Something went wrong!</div>;    }    return this.props.children;  } } export default ErrorBoundary;

Using the Error Boundary:

Wrap the components you want to be covered by the error boundary using the ErrorBoundary component.

jsxCopy code

// App.js import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; import { ThemeProvider } from './ThemeContext'; import Home from './Home'; import About from './About'; import Products from './Products'; import ErrorBoundary from './ErrorBoundary'; function App() {  return (    <Router>      <ThemeProvider>        <div>          <h1>Hello, React!</h1>          <nav>            <ul>              <li>                <Link to="/">Home</Link>              </li>              <li>                <Link to="/about">About</Link>              </li>              <li>                <Link to="/products">Products</Link>              </li>            </ul>          </nav>          <ErrorBoundary>            <Route exact path="/" component={Home} />            <Route path="/about" component={About} />            <Route path="/products" component={Products} />          </ErrorBoundary>        </div>      </ThemeProvider>    </Router>  ); } export default App;

In this example, we wrapped the Route components with the ErrorBoundary to catch any errors that may occur during rendering.

Step 3: useReducer Hook

The useReducer hook is an alternative to useState that allows you to handle more complex state logic. It uses a reducer function to update the state based on dispatched actions.

jsxCopy code

import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => {  switch (action.type) {    case 'INCREMENT':      return { count: state.count + 1 };    case 'DECREMENT':      return { count: state.count - 1 };    default:      return state;  } }; const Counter = () => {  const [state, dispatch] = useReducer(reducer, initialState);  return (    <div>      <h2>Count: {state.count}</h2>      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>    </div>  ); }; export default Counter;

In this example, we use useReducer to manage the state of the Counter component. The reducer function handles different actions (INCREMENT and DECREMENT) to update the state.

Step 4: useRef Hook

The useRef hook allows you to create a mutable reference that persists across renders. It is useful for accessing DOM elements, managing previous state values, and avoiding unnecessary re-renders.

jsxCopy code

import React, { useRef } from 'react'; const InputWithFocus = () => {  const inputRef = useRef(null);  const handleClick = () => {    inputRef.current.focus();  };  return (    <div>      <input type="text" ref={inputRef} />      <button onClick={handleClick}>Focus Input</button>    </div>  ); }; export default InputWithFocus;

In this example, we use useRef to create a reference to the input element. When the button is clicked, the handleClick function sets the focus on the input element using the focus() method.

Congratulations! You've completed the third class of React Advanced. You've learned about React context, error boundaries, using the useReducer and useRef hooks.

React offers a vast array of tools and techniques to build powerful and performant applications. As you continue your React journey, you can explore more advanced topics such as server-side rendering (SSR), integrating with state management libraries like Redux, using custom hooks, and exploring more complex use cases of context.

Keep practicing, building more complex applications, and exploring the vast possibilities of React! Happy coding!

15. React Advance

Comments: 24

profile
22-Jul-2024, 10:33 PM

Kindly check the lecture number 6. Lifecycle of a Change in 1. Git and Github The above lecture is not related to the course please update it ASAP Thank you

profile
@harshp.cs.22
10-Jul-2024, 03:37 PM

From where can I download the files which love babbar says he has uploaded on dashboard ??

profile
23-Jul-2024, 12:05 PM

I have attached the link https://github.com/lakshayk12/ANN_optimization_BTP

profile
@sudiptamondal787
10-Jul-2024, 02:40 AM

bro, i paid for the course, but still can't access the course. do something

profile
@zubaid.zu
9-May-2024, 02:42 AM

Paid for the course but it still locked, can solve this problem please, when you take the payment the couse should be unlocked, evey time i have to message for any purchase

profile
@admin79
10-May-2024, 10:29 PM

Now your Paypal payment is accepted and your course is activated successfully. Please leave your valuable feedback.

profile
@anandwising
12-Mar-2024, 04:05 PM

Why i am being asked for payment if i am already enrolled in the course

profile
@admin79
12-Mar-2024, 05:22 PM

Dear anand, your payment is now updated check your course, apologize for several delays. Please leave your valuable feedback.

profile
@anandwising
12-Mar-2024, 08:33 PM

thanks its working now

profile
@Megha
22-Feb-2024, 11:02 PM

hello ,I have a doubt

profile
@akshaykumrawat99
22-Feb-2024, 10:56 PM

hello i have a doubt

profile
@rajnireddyatr
3-Feb-2024, 12:08 AM

hi

profile
@talha.developments
18-Jan-2024, 09:34 PM

I'm paying through my Card, but it giving an error. why ? how we can purchase a course in Pakistan. Paypal is banned here

profile
@aryangrg020
17-Jan-2024, 10:25 PM

can we download the videos

profile
@Krishanpal
14-Jan-2024, 08:12 PM

i done my payment for mern stack development love babbar but cant acces to course kindly give me access

profile
@sciaku1
17-Jan-2024, 12:28 PM

Dear Krishnapal your payment is already accepted go and check back.

profile
@shivanshgautam220
10-Jan-2024, 04:57 PM

Why i am being asked for payment if i am already enrolled in the course

profile
@sciaku1
11-Jan-2024, 03:18 PM

Dear Shivansh, if you already done your payment then contact us on our official Email id [email protected] or reply here.

profile
@p8354046
7-Jan-2024, 03:47 PM

Why i am being asked for payment if i am already enrolled in the course

profile
@sciaku1
11-Jan-2024, 03:19 PM

Dear p8354046, if you already done your payment then contact us on our official Email id [email protected] or reply here.

profile
@myidontablet
30-Dec-2023, 04:28 PM

Why i am being asked for payment if i am already enrolled in the course

profile
@sciaku1
6-Jan-2024, 01:42 AM

Dear, Don't worry now your problem is solved check your id.

profile
@duabhi911
16-Nov-2023, 02:03 AM

Why i am being asked for payment if i am already enrolled in the course

profile
@harshp.cs.22
23-Dec-2023, 11:40 AM

Yes bro

profile
@myidontablet
30-Dec-2023, 04:28 PM

I'm facing same issue

profile
@sciaku1
6-Jan-2024, 01:43 AM

Dear, Don't worry now your problem is solved check your id.

profile
@lenientharsh
31-Oct-2023, 10:56 AM

i want debit card option

profile
@lenientharsh
31-Oct-2023, 10:51 AM

how can i assure that this is not scam?

profile
@jainarin416
2-Nov-2023, 12:37 AM

i have same doubt is this website real or a fraud

profile
@sciaku1
6-Jan-2024, 01:45 AM

No its not any fraud. its genuine if you need any proof please contact us via email.

profile
@sciaku1
6-Jan-2024, 01:44 AM

No it's not any scam, its genuine if you need any proof please contact us via email.

profile
@hydrarishabh9
21-Oct-2023, 11:47 PM

how to do payment ?

profile
@sciaku1
30-Oct-2023, 05:34 PM

Click on Watch now button then click next video then payment option is showing

profile
@minhajakram440
18-Oct-2023, 11:18 PM

i am unable to access the video even i have already completed my payment .

profile
@aeromusgyan
21-Oct-2023, 01:17 AM

Your problem is solved

profile
@saklyi70
30-Sep-2023, 11:02 AM

plz add codes lecture wise ! it wold be great and helpful also

profile
@sciaku1
6-Jan-2024, 01:47 AM

now we have added starter package in lecture 2nd, go now and download it.

profile
@thomasroka31
29-Sep-2023, 04:05 PM

how to view this one

profile
@jitendrakrverma02
23-Sep-2023, 03:57 PM

Why video not play

profile
@sciaku1
6-Jan-2024, 01:47 AM

Now it's working.

profile
@9035praveen
2-Sep-2023, 12:12 PM

Thank you for the access of the videos. It would be greatful if I could no the way to download the videos

profile
@mohammedunaismdr
25-Sep-2023, 11:54 AM

Use idm to download

profile
@mishraprajjwal295
13-Oct-2023, 11:07 PM

ok

profile
@rahulkumarbaraswal30
4-Nov-2023, 01:32 PM

Hello bro can you share course with me?

profile
@bicky
1-Sep-2023, 05:42 PM

hello everyone

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?