In my component I use a function which I want to extract, it uses some hooks for setting url params. I created a custom hook.
function useMyCustomHook() {
const history = useHistory();
const location = useLocation();
const locationParams = new URLSearchParams(location.search);
function myCustomHook(id: string ) {
does something
}
return myCustomHook;
}
So I extracted it like shown above and now I want to use it in my other component and inside a useEffect hook.
const { myCustomHook } = useMyCustomHook(); // It asks me to add parameters,
but I want to pass it inside useEffect
useEffect(() => {
if (something) myCustomHook(myParam);
}, [foo]);
Is this a possible approach? Or is there a better solution where I can extract something with hooks and then reuse it in useEffect with parameters? Thank you!
First you need export your custom Hook, I think if you need return a function with id, that function need be executed each id change.
custom hook
import { useCallback} from "react"
import {useNavigate, useLocation} from "react-router-dom"
export const useMyCustomHook = (id) => {
const navigate = useNavigate() // React-router v6
const location = useLocation()
const locationParams = new URLSearchParams(location.search)
const anyFunction = useCallback(() => {
// does something
}, [id]) // the function execute if "id" change
return anyFunction
}
where you wanna use your custom hook
import {useMyCustomHook} from "your router"
const {anyFunction} = useMyCustomHook(id) // your pass the id
useEffect(() => {
if (something) anyFunction()
}, [foo])
I think this is the better way. useCallback only render the function of the params change.
Related
I am trying to learn to work with custom Hooks in React-native. I am using AWS Amplify as my backend, and it has a method to get the authenticated user's information, namely the Auth.currentUserInfo method. However, what it returns is an object and I want to make a custom Hook to both returns the part of the object that I need, and also abstract away this part of my code from the visualization part. I have a component called App, and a custom Hook called useUserId. The code for them is as follows:
The useUserId Hook:
import React, { useState, useEffect } from "react";
import { Auth } from "aws-amplify";
const getUserInfo = async () => {
try {
const userInfo = await Auth.currentUserInfo();
const userId = userInfo?.attributes?.sub;
return userId;
} catch (e) {
console.log("Failed to get the AuthUserId", e);
}
};
const useUserId = () => {
const [id, setId] = useState("");
const userId = getUserInfo();
useEffect(() => {
userId.then((userId) => {
setId(userId);
});
}, [userId]);
return id;
};
export default useUserId;
The App component:
import React from "react";
import useUserId from "../custom-hooks/UseUserId";
const App = () => {
const authUserId = useUserId();
console.log(authUserId);
However, when I try to run the App component, I get the same Id written on the screen twice, meaning that the App component is executed again.
The problem with this is that I am using this custom Hook in another custom Hook, let's call it useFetchData that fetches some data based on the userId, then each time this is executed that is also re-executed, which causes some problems.
I am kind of new to React, would you please guide me on what I am doing wrong here, and what is the solution to this problem. Thank you.
The issue is likely due to the fact that you've declared userId in the hook body. When useUserId is called in the App component it declares userId and updates state. This triggers a rerender and userId is declared again, and updates the state again, this time with the same value. The useState hook being updated to the same value a second time quits the loop.
Bailing out of a state update
If you update a State Hook to the same value as the current state,
React will bail out without rendering the children or firing effects.
(React uses the Object.is comparison algorithm.)
Either move const userId = getUserInfo(); out of the useUserId hook
const userId = getUserInfo();
const useUserId = () => {
const [id, setId] = useState("");
useEffect(() => {
userId.then((userId) => {
setId(userId);
});
}, []);
return id;
};
or more it into the useEffect callback body.
const useUserId = () => {
const [id, setId] = useState("");
useEffect(() => {
getUserInfo().then((userId) => {
setId(userId);
});
}, []);
return id;
};
and in both cases remove userId as a dependency of the useEffect hook.
Replace userId.then with to getUserId().then. It doesn't make sense to have the result of getUserId in the body of a component, since it's a promise and that code will be run every time the component renders.
I'm using a React Context const Context = React.createContext() with a useEffect hook to set a variable in my outer-most component that wraps my entire app. On a child component within my app I am using history.push('/') to route back to the root. This does not appear to trigger an update on my Context variable. Is this expected? If so, is there a better way to route that would update my context variable?
I'm using react 16.14.0 & react-router-dom 5.2.0.
For example, in the code below. Shouldnt var increment on history.push('/')
Context.js
const Context= React.createContext();
const ContextProvider= (props) => {
const [var, setVar] = useState(null);
useEffect(() => {
setVar(var++)
}, []);
return (
<Context.Provider value={user}>{props.children}</Context.Provider>
);
};
ChildComponent.js
...
import { useHistory } from "react-router-dom";
...
const ChildComponent = () => {
const history = useHistory();
function doSomething(){
history.push('/')
}
}
return(
<Button onClick={() => doSomething()} />
)
This does not appear to trigger an update on my Context variable. Is this expected?
Changing the history does not cause context providers to rerender. You mention you have a useEffect, and in principle you could write some code in that useEffect which would listen to the history, and when it gets a change it sets state to cause a rerender. If you have code in there that you think is supposed to listen for history changes, feel free to share that and i'll comment on it.
However, instead of writing your own code to listen for changes, i'd recommend using the hooks provided by react-router. The useHistory and useLocation hooks will both listen for changes and rerender the component.
const Example = () => {
// When the location changes, Example will rerender
const location = useLocation();
const [someState, setSomeState] = useState('foo');
useEffect(() => {
if (/* check something you care about in the location */) {
setSomeState('bar');
}
}, [location]);
return (
<Context.Provider value={someState}>
{children}
</Context.Provider>
)
}
I have a function that handles React Native location. For demonstration:
const useLocation = () => {
const [fetchingLocation, setFetchingLocation] = useState(true);
...
const changeSystemPermissions = useCallback(() => {...});
useEffect(() => {
//does many things
}, [...])
}
I need to have the function changeSystemPermissions inside useLocation as it uses the state.
I realize that I can export the changeSystemPermissions function as a const with a return [changeSystemPermissions, ...] and then import it in another component with:
const [
changeSystemPermissions,
...
] = useLocation();
However, it will ALSO run the useEffect function. I do want it to run once, but I need to access changeSystemPermissions in several other components and I don't want the useEffect to run multiple times.
I was thinking I will just take out the changeSystemPermissions function outside of useLocation, but it needs to use the state. I suppose I COULD pass the state vars into the changeSystemPermissions when it is outside useLocation, but that would be verbose and ugly.
How can I export changeSystemPermissions and just that function without having to import the whole useLocation function?
Can you move the useEffect to the component one ?
const useLocation = () => {
const [fetchingLocation, setFetchingLocation] = useState(true);
const changeSystemPermissions = useCallback(() => {
...
});
const funcToExecute = useCallback(() => {
....
}, []);
return { changeSystemPermissions, funcToExecute }
}
And put it in the component :
const {
changeSystemPermissions,
funcToExecute,
} = useLocation();
useEffect(() => {
funcToExecute()
}, [...])
Also, if you really need the useEffect to be in the custom hook,
maybe you can add a param to this hook.
const useLocation = (shouldTriggerEffect) => {
const [fetchingLocation, setFetchingLocation] = useState(true);
const changeSystemPermissions = useCallback(() => {
...
});
useEffect(() => {
if (shouldTriggerEffect) {
...
}
}, [shouldTriggerEffect])
return { changeSystemPermissions, funcToExecute }
}
And then in the component,
const {
changeSystemPermissions,
} = useLocation(false);
Tell me if I misunderstood something or if it helps :)
When ever you call a hook inside a React functional component, it will create a new state for that hook and not sharing among components. But there is a library which could help you achieve that:
https://github.com/betula/use-between
You could follow example to use this library or maybe just read the code and utilize the approach for your case to share the hook state between components.
I have a react native screen that has a very long code that I would like to refractor.
Say my screen.jsx is (simplified, of course):
import React, { useState, useCallback, useEffect } from 'react';
import useLocation from '../hooks/useLocation'; // A custom hook I wrote. This one makes sense to use as a hook. It's a function that returns a location.
...
export default function Screen() {
const [fetchingLocation, region, setRegion] = useLocation();
// FROM HERE DOWN
const [fetchingRestaurants, setFetchingRestaurants] = useState(false);
const [restaurants, setRestaurants] = useState([]);
const [errorMessage, setErrorMessage] = useState('');
const initSearch = useCallback(async ({ searchQuery, region }) => {
setFetchingRestaurants(true);
try {
const response = await remoteApi.get('/search', {
params: {
term: searchQuery,
latitude: region.latitude,
longitude: region.longitude,
},
});
const fetchedRestaurants = response.data.businesses;
const fetchedRestaurantsArray = fetchedRestaurants.map((restaurant) => ({
id: restaurant.id,
name: restaurant.name,
}));
setRestaurants(fetchedRestaurantsArray);
setFetchingRestaurants(false);
} catch (e) {
setRestaurants([]);
setFetchingRestaurants(false);
}
}, []);
return (
<View>...</View>
);
}
To better structure my code, I would like to move all the code you see below "FROM HERE DOWN" (initSearch as well as the three state management useState hooks above it) into another file and import it.
At the moment I created a custom useRestaurantSearch hook in the hooks folder like so:
export default function useRestaurantSearch() {
// The code I mentioned goes here
return [initSearch, errorMessage, restaurants, setRestaurants, fetchingRestaurants];
}
Then in my Screen.jsx file I import it import useRestaurantSearch from '../hooks/useRestaurantSearch'; and inside function Screen() I grab the consts I need with
const [
initSearch,
errorMessage,
restaurants,
setRestaurants,
fetchingRestaurants,
] = useRestaurantSearch();
This works, but I feel like it can be better written and this whole approach seems weird - is it really a custom hook? If it's not a custom hook, does it belong in a util folder as a utility?
How would you approach this?
Yes this would be considered a custom hook since according to the React docs, custom hooks are just a mechanism to reuse stateful logic.
One thing that could help simplify it is:
using a library like TanStack Query (formerly React Query). You could create a query to fetch the restaurants and then you could use the data and fetchStatus from the query instead of adding them to state.
I have the main component along with local state using useState and useRef, I also another custom hook, inside the custom hook I would like to reset my main component's state and ref, am I doing correctly by below?
// custom hook
const useLoadData = ({startLoad, setStartLoad, setLoadCompleted, setUserNameRef}) => {
useEffect(() => {
const fetchUser = async() => { await fetchFromApi(...); return userName;};
if (startLoad) {
const newUserName = fetchUser();
setStartLoad(false);
setLoadCompleted(true);
setUserNameRef(newUserName);
}
}, [startLoad]);
}
// main component
const myMainComp = () {
const [startLoad, setStartLoad] = useState(false);
const [loadCompleted, setLoadCompleted] = useState(false);
const userNameRef = useRef("");
const setUserNameRef = (username) => { this.userNameRef.current = username; }
useLoadData(startLoad, setStartLoad, setLoadCompleted, setUserNameRef);
refreshPage = (userId) => {
setStartLoad(true);
}
}
Am I using the custom hook correctly like by passing all external state value and setState method in? Also I found even I don't use useEffect in my customHook, it also works as expected, so do I need to use useEffect in my custom hook? Any review and suggestion is welcome!
First, I think isn't a good approach you use component methods inside custom hook (like "set" methods provided by useState). You are binding the hook with the main component's internal logic. If the purpose of custom hook is fetch data from API, it need to provide to main component the vars that can be able the main component to manipulate its state by itself (like return isFetching, error, data, etc. and don't call any main component set method inside hook).