If you have any query feel free to chat us!
Happy Coding! Happy Learning!
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
anduseRef
.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
usingcreateContext
and provided aThemeProvider
component that wraps its children with theThemeContext.Provider
. It holds thetheme
state and thesetTheme
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 thetheme
state andsetTheme
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 theErrorBoundary
to catch any errors that may occur during rendering.Step 3: useReducer Hook
The
useReducer
hook is an alternative touseState
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 theCounter
component. Thereducer
function handles different actions (INCREMENT
andDECREMENT
) 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, thehandleClick
function sets the focus on the input element using thefocus()
method.Congratulations! You've completed the third class of React Advanced. You've learned about React context, error boundaries, using the
useReducer
anduseRef
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!
Comments: 24
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
From where can I download the files which love babbar says he has uploaded on dashboard ??
I have attached the link https://github.com/lakshayk12/ANN_optimization_BTP
bro, i paid for the course, but still can't access the course. do something
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
Now your Paypal payment is accepted and your course is activated successfully. Please leave your valuable feedback.
Why i am being asked for payment if i am already enrolled in the course
Dear anand, your payment is now updated check your course, apologize for several delays. Please leave your valuable feedback.
thanks its working now
hello ,I have a doubt
hello i have a doubt
hi
I'm paying through my Card, but it giving an error. why ? how we can purchase a course in Pakistan. Paypal is banned here
can we download the videos
i done my payment for mern stack development love babbar but cant acces to course kindly give me access
Dear Krishnapal your payment is already accepted go and check back.
Why i am being asked for payment if i am already enrolled in the course
Dear Shivansh, if you already done your payment then contact us on our official Email id [email protected] or reply here.
Why i am being asked for payment if i am already enrolled in the course
Dear p8354046, if you already done your payment then contact us on our official Email id [email protected] or reply here.
Why i am being asked for payment if i am already enrolled in the course
Dear, Don't worry now your problem is solved check your id.
Why i am being asked for payment if i am already enrolled in the course
Yes bro
I'm facing same issue
Dear, Don't worry now your problem is solved check your id.
i want debit card option
how can i assure that this is not scam?
i have same doubt is this website real or a fraud
No its not any fraud. its genuine if you need any proof please contact us via email.
No it's not any scam, its genuine if you need any proof please contact us via email.
how to do payment ?
Click on Watch now button then click next video then payment option is showing
i am unable to access the video even i have already completed my payment .
Your problem is solved
plz add codes lecture wise ! it wold be great and helpful also
now we have added starter package in lecture 2nd, go now and download it.
how to view this one
Why video not play
Now it's working.
Thank you for the access of the videos. It would be greatful if I could no the way to download the videos
Use idm to download
ok
Hello bro can you share course with me?
hello everyone