#react uselocation
Explore tagged Tumblr posts
Text
#How to Use Location Hook in React Router DOM V6#react router uselocation#use location react router#uselocation#react uselocation#uselocation react-router#react uselocation search#uselocation react router#react-router-dom uselocation#Step By Step Tutorials
0 notes
Video
youtube
How to Pass Object to Another Component in React using useLocation()
0 notes
Text
You can learn ReactJS easily, Here's all you need to get started:
1.Components
• Functional Components
• Class Components
• JSX (JavaScript XML) Syntax
2.Props (Properties)
• Passing Props
• Default Props
• Prop Types
3.State
• useState Hook
• Class Component State
• Immutable State
4.Lifecycle Methods (Class Components)
• componentDidMount
• componentDidUpdate
• componentWillUnmount
5.Hooks (Functional Components)
• useState
• useEffect
• useContext
• useReducer
• useCallback
• UseMemo
• UseRef
• uselmperativeHandle
• useLayoutEffect
6.Event Handling
• Handling Events in Functional Components
• Handling Events in Class Components
7.Conditional Rendering
• it Statements
• Ternary Operators
• Logical && Operator
8.Lists and Keys
• Rendering Lists
• Keys in React Lists
9.Component Composition
• Reusing Components
• Children Props
• Composition vs Inheritance
10.Higher-Order Components (HOC)
• Creating HOCs
• Using HOCs for Reusability
11.Render Props
• Using Render Props Pattern
12.React Router
• <BrowserRouter>
• <Route>
• <Link>
• <Switch>
• Route Parameters
13. Navigation
• useHistory Hook
• useLocation Hook
State Management
14.Context API
• Creating Context
• useContext Hook
15.Redux
• Actions
• Reducers
• Store
• connect Function (React-Redux)
16.Forms
• Handling Form Data
• Controlled Components
• Uncontrolled Components
17.Side Effects
• useEffect for Data Fetching
• useEffect Cleanup
18.AJAX Requests
• Fetch AP
• Axios Library
Error Handling
19.Error Boundaries
• componentDidCatch (Class Components)
• ErrorBoundary Component (Functional
Components)
20.Testing
• Jest Testing Framework
• React Testing Library
21. Best Practices
• Code Splitting
• PureComponent and React.memo
• Avoiding Reconciliation
• Keys for Dynamic Lists
22.Optimization
• Memoization
• Profiling and Performance Monitoring
23. Build and Deployment
• Create React App (CRA)
• Production Builds
• Deployment Strategies
Frameworks and Libraries
24.Styling Libraries
• Styled-components
• CSS Modules
25.State Management Libraries
• Redux
• MobX
26.Routing Libraries
• React Router
• Reach Router
0 notes
Text
Passing URL parameters to a route using useParams in react-router-dom version 6
https://vikasprogramming.blogspot.com/2021/12/passing-url-parameters-to-route-using-useParams-react-router-dom-v6.html
#ReactJs redux useLocation useNavigate react-router react-router-dom javascript vikasprograming programming web development programming webde#route#routing#useParams
0 notes
Video
youtube
Build Web 3.0 AirBNB Clone Using web3uikit, React, Moralis and Solidity - Full-Stack Blockchain App
https://youtu.be/rj-Mb-xz1Os
1시간 30분분량 airbnb 웹사이트를 web로 구현 moralis를 이용하는데 내용이 굉장히 좋다.
using state hook usetState() https://reactjs.org/docs/hooks-state.html
.
const { fill:fillOld } = propsOld
https://stackoverflow.com/a/54311500
.
react router useLocation
https://v5.reactrouter.com/web/api/Hooks/uselocation
.
using effet hook useEffect()
https://reactjs.org/docs/hooks-effect.html
.
react router <Link> state
https://reactjs.org/docs/hooks-effect.html
.
특정 변수의 값변화에만 작동하는 useEffect()만들기
https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
.
javascript ()()
https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
.
string compare keccak256
https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
.
payable(addr)
https://ethereum.stackexchange.com/a/82771
1 note
·
View note
Photo
React router with hooks ( useHistory useParam useLocation ) ☞ https://bit.ly/2AKAZVP #reactjs #javascript
1 note
·
View note
Link
React as a framework
React has been out in the world of web development for quite some time now and its position as a tool for agile web development has steadily strengthened in recent years. Especially after the announcement and release of the new hook api/concept, writing components has never been easier. Although the team behind react and the huge community have tried to train and explain the concepts of the framework in an impressive way, I still see some pitfalls and common mistakes that were made while working with it. I kept a list of all the mistakes I saw over the last years related to react especially with using hooks. In this article I want to show you the most common ones and I will also try to explain in detail, why I think they are mistakes and a suggestion for doing it in a cleaner way.
Disclaimer
Before we start with the list, I have to say that most of the following things are not fundamental mistakes or don't look wrong at first glance, and also most of them are unlikely to affect the performance or apperance of the application. Probably nobody would notice, except for the developers working on the product, that something is wrong here, but I still believe that good quality code can lead to a better developer experience and thus to a better product. As with any software framework or library, there are millions of different opinions about it. Everything you see here is based on my personal opinion and should not be considered a general rule. If you have a different opinion about her, I would love to hear it 🌟
1. Using useState when no rerender is needed
One of the core concepts of react is dealing with state. You can control your entire data flow and rendering through the state. Each time the tree is rendered again, it is most likely tied to a change in the state. With the useState hook you can now also define your state in function components, which is a really neat and easy way how to handle states in react. But it can also be misused as we see in the following example. For the next example we need a bit of explanation, suppose we have two buttons, one button is a counter and the other button sends a request or triggers an action with the current count. However, the current number is never displayed within the component. It is only required for the request when you click the second button.
This is dangerous ❌
function ClickButton(props) { const [count, setCount] = useState(0); const onClickCount = () => { setCount((c) => x + 1); }; const onClickRequest = () => { apiCall(count); }; return ( <div> <button onClick={onClickCount}>Counter</button> <button onClick={onClickRequest}>Submit</button> </div> ); }
The problem ⚡
At the first sight, you might ask what is exactly the problem with that? Isn't what what the state was made for? Sure you are right, this will work just fine and probably there will be never a problem with that, however in react every state change will force a rerender for that component and most likely its children, but in the above example since we never use that state in our render part, this will end up being an unnecessary render every time we set the counter, which can impact the performance or could have unexpected side effects.
The solution ✅
If you want to use a variable inside your component which should keep its value between rendering but also don't force a rerender, you can use the useRef hook. It will keep the value, but doesn't force the component to rerender.
function ClickButton(props) { const count = useRef(0); const onClickCount = () => { count.current++; }; const onClickRequest = () => { apiCall(count); }; return ( <div> <button onClick={onClickCount}>Counter</button> <button onClick={onClickRequest}>Submit</button> </div> ); }
2. Using router.push instead of a link
This might be a very easy and obvious one and not really related to react itself, but I still see it quite a lot when people writing react components. Let's say you will write a button and with clicking the button the user should be redirected to another page. Since its a SPA, this action will be a client-side routing mechanism. So you will need some kind of library for doing that. In react the most popular one is react-router and the following example will use that library. So adding a click listener will redirect the user to the desired page right?
This is dangerous ❌
function ClickButton(props) { const history = useHistory(); const onClick = () => { history.push('/next-page'); }; return <button onClick={onClick}>Go to next page</button>; }
The problem ⚡
Even though this would work just fine for most of the users, there is huge problem when it comes to accessibility here. The button will not be marked as linking to another page at all, which makes it nearly impossible to be identified by screen readers. Also could you open that in a new tab or window? Most likely not.
The solution ✅
Linking to other pages with any user interaction should as far as possible be handled by the <Link> component or a normal <a> tag.
function ClickButton(props) { return ( <Link to="/next-page"> <button>Go to next page</button> </Link> ); }
Bonus points: it also makes the code a lot more readable and shorter!
3. Handling actions via useEffect
One of the best and most thoughtful hooks introduced by React is the "useEffect" hook. It enables the processing of actions related to prop or state changes. Despite its helpful functionality, it is also often used in places where it may not be needed. Imagine a component that fetches a list of items and render them to the dom. In addition, if the request is successful, we would like to call the "onSuccess" function, which is passed on to the component as a prop
This is dangerous ❌
function ClickButton(props) { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [data, setData] = useState(null); const fetchData = useCallback(() => { setLoading(true); callApi() .then((res) => setData(res)) .catch((err) => setError(err)) .finally(() => setLoading(false)); }, []); useEffect(() => { fetchData(); }, [fetchData]); useEffect(() => { if (!loading && !error && data) { props.onSuccess(); } }, [loading, error, data]); return <div>{data}</div>; }
The problem ⚡
There are two useEffect hooks, the first one is handling the api call on the initial render and the second one will call the onSuccess function, by assuming when there is no loading, no error, but data in the state, it must have been a successful call. Make sense right? Sure for the first call this is true and probably will never fail. But you also loose the direct connection between the action and the function that needs to be called. Also there is no 100% guarantee that this case will only happen if the fetch action has succeeded and this is something we as developers really don't like.
The solution ✅
A straight forward solution would be to set the "onSuccess" function to the actual place where the call was successful:
function ClickButton(props) { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [data, setData] = useState(null); const fetchData = useCallback(() => { setLoading(true); callApi() .then((fetchedData) => { setData(fetchedData); props.onSuccess(); }) .catch((err) => setError(err)) .finally(() => setLoading(false)); }, [props.onSuccess]); useEffect(() => { fetchData(); }, []); return <div>{data}</div>; }
Now it is quite clear at the first sight when the onSuccess is called, exactly in the success case of the api call.
4. Single responsibility components
Composing components can be hard. When is it time to split a component into several smaller components? How do you structure the component tree? All of these questions arise every day when working with a component-based framework. However, a common mistake in designing your components is to combine two use cases into a single component. Let's take an example of a header that shows either a burger button on mobile devices or tabs on desktop screens. (The condition will be handled the the magical isMobile function, which is not part of this example 🧙)
This is dangerous ❌
function Header(props) { return ( <header> <HeaderInner menuItems={menuItems} /> </header> ); } function HeaderInner({ menuItems }) { return isMobile() ? <BurgerButton menuItems={menuItems} /> : <Tabs tabData={menuItems} />; }
The problem ⚡
With this approach the component HeaderInner is trying to be two different things at once and we all learned from Mr. Jekyll, being more than one thing at a time isn't really ideal. Also it makes it even hard to test or to reuse the component at other places.
The solution ✅
Bringing the condition one level up, makes it easier to see what the components are made for and that they only have one responsibility, being a Header, Tabs or a BurgerButton and not trying to be two things at once.
function Header(props) { return ( <header>{isMobile() ? <BurgerButton menuItems={menuItems} /> : <Tabs tabData={menuItems} />}</header> ); }
5. Single responsibility useEffects
Remember the times, where we only had the componentWillReceiveProps or componentDidUpdate methods to hook into the rendering process of a react component? It is bringing back dark memories and also realizing the beauty of using the useEffect hook and especially that you can have as much as you want of them. But sometimes forgetting and using a "useEffect" for several things brings back those dark memories. For example, imagine you have a component that fetches some data from the backend in some way, and also displays breadcrumbs depending on the current location. (Using again react-router for getting the current location.)
This is dangerous ❌
function Example(props) { const location = useLocation(); const fetchData = useCallback(() => { /* Calling the api */ }, []); const updateBreadcrumbs = useCallback(() => { /* Updating the breadcrumbs*/ }, []); useEffect(() => { fetchData(); updateBreadcrumbs(); }, [location.pathname, fetchData, updateBreadcrumbs]); return ( <div> <BreadCrumbs /> </div> ); }
The problem ⚡
There are two use cases, the "data-fetching" and "displaying breadcrumbs". Both are updated with an useEffect hook. This single useEffect hooks will run when the fetchData and updateBreadcrumbs functions or the location changes. The main problem is now, we also call the fetchData function when the location changes. This might be a side effect we haven't thought of.
The solution ✅
Splitting up the effect makes sure, they only are used for one effect and the unexpected side effects are gone.
function Example(props) { const location = useLocation(); const updateBreadcrumbs = useCallback(() => { /* Updating the breadcrumbs*/ }, []); useEffect(() => { updateBreadcrumbs(); }, [location.pathname, updateBreadcrumbs]); const fetchData = useCallback(() => { /* Calling the api */ }, []); useEffect(() => { fetchData(); }, [fetchData]); return ( <div> <BreadCrumbs /> </div> ); }
Bonus Points, the use cases are now also logically sorted within the component.
Conclusion
There are many pitfalls when writing components in react. It is never 100% possible to understand the whole mechanism and to avoid every little or even big mistake. But making mistakes is also important when learning a framework or programming language and probably nobody is 100% free of these mistakes. I think sharing your experience with that can be very helpful for others or prevent them from making them. If you have any questions or wait, I don't think this is a mistake, please write to me, I would love to hear your opinion.
0 notes
Text
The Hooks of React Router
React Router 5 embraces the power of hooks and has introduced four different hooks to help with routing. You will find this article useful if you are looking for a quick primer on the new patterns of React Router. But before we look at hooks, we will start off with a new route rendering pattern.
Before React Router 5
// When you wanted to render the route and get router props for component <Route path="/" component={Home} />
// Or when you wanted to pass extra props <Route path="/" render={({ match }) => <Profile match={match} mine={true} />}>
When using the component syntax, route props (match, location and history) are implicitly being passed on to the component. But it has to be changed to render once you have extra props to pass to the component. Note that adding an inline function to the component syntax would lead to the component re-mounting on every render.
After React Router 5
<Route path="/"> <Home /> </Route>
Note that there is no implicit passing of any props to the Home component. But without changing anything with the Route itself, you can add any extra props to the Home component. You can no longer make the mistake of re-mounting the component on every render and that's the best kind of API.
But now route props are not being passed implicitly, so how do we access match, history or location? Do we have to wrap all components with withRouter? That is where the hooks steps in.
Note that hooks were introduced in 16.8 version of React, so you need to be above that version to use them.
useHistory
Provides access to the history prop in React Router
Refers to the history package dependency that the router uses
A primary use case would be for programmatic routing with functions, like push, replace, etc.
import { useHistory } from 'react-router-dom'; function Home() { const history = useHistory(); return <button onClick={() => history.push('/profile')}>Profile</button>; }
useLocation
Provides access to the location prop in React Router
It is similar to window.location in the browser itself, but this is accessible everywhere as it represents the Router state and location.
A primary use case for this would be to access the query params or the complete route string.
import { useLocation } from 'react-router-dom'; function Profile() { const location = useLocation(); useEffect(() => { const currentPath = location.pathname; const searchParams = new URLSearchParams(location.search); }, [location]); return <p>Profile</p>; }
Since the location property is immutable, useEffect will call the function every time the route changes, making it perfect to operate on search parameters or current path.
useParams
Provides access to search parameters in the URL
This was possible earlier only using match.params.
import { useParams, Route } from 'react-router-dom'; function Profile() { const { name } = useParams(); return <p>{name}'s Profile</p>; } function Dashboard() { return ( <> <nav> <Link to={`/profile/ann`}>Ann's Profile</Link> </nav> <main> <Route path="/profile/:name"> <Profile /> </Route> </main> </> ); }
useRouteMatch
Provides access to the match object
If it is provided with no arguments, it returns the closest match in the component or its parents.
A primary use case would be to construct nested paths.
import { useRouteMatch, Route } from 'react-router-dom'; function Auth() { const match = useRouteMatch(); return ( <> <Route path={`${match.url}/login`}> <Login /> </Route> <Route path={`${match.url}/register`}> <Register /> </Route> </> ); }
You can also use useRouteMatch to access a match without rendering a Route. This is done by passing it the location argument.
For example, consider that you need your own profile to be rendered at /profile and somebody else's profile if the URL contains the name of the person /profile/dan or /profile/ann. Without using the hook, you would either write a Switch, list both routes and customize them with props. But now, using the hook we can do this:
import { Route, BrowserRouter as Router, Link, useRouteMatch, } from 'react-router-dom'; function Profile() { const match = useRouteMatch('/profile/:name'); return match ? <p>{match.params.name}'s Profile</p> : <p>My own profile</p>; } export default function App() { return ( <Router> <nav> <Link to="/profile">My Profile</Link> <br /> <Link to={`/profile/ann`}>Ann's Profile</Link> </nav> <Route path="/profile"> <Profile /> </Route> </Router> ); }
You can also use all the props on Route like exact or sensitive as an object with useRouteMatch.
Wrapping up
The hooks and explicit Route comes with a hidden advantage in itself. After teaching these techniques at multiple workshops, I have come to the realization that these help avoid a lot of confusion and intricacies that came with the earlier patterns. There are suddenly far fewer unforced errors. They will surely help make your router code more maintainable and you will find it way easier to upgrade to new React Router versions.
The post The Hooks of React Router appeared first on CSS-Tricks.
The Hooks of React Router published first on https://deskbysnafu.tumblr.com/
0 notes
Text
useNavigate & useLocation hooks react-router-dom-v6
https://vikasprogramming.blogspot.com/2022/01/usenavigate-uselocation-hooks-react.html
#ReactJs #redux #useLocation #useNavigate #react-router #react-router-dom #javascript #vikasprograming #programming #web #development #programming #webdeveloper #reacthooks #typescript #html #css #html5 #bootstrap #ui #designing #uidesigner #uidevelopment #route #routing #routes
0 notes