Here i have a example hooks
const useGPS = () => {
const [gps, setGps] = useState({})
useEffect(() => {
setGps({ a: 1 })
}, [])
return [gps]
}
it's pretty simple, but when i use it inside another Component
const Foo = () => {
const location = useGPS()
useEffect(() => {
console.log(location);
}, [])
return (
<div>1</div>
)
}
console always log empty object for first time. Can someone explain what happened and how can i fix it? Sorry about my bad english. Thanks a lot!
The value of GPS is only set after the first useEffect is run (inside the custom hook). It is initially empty and when the useEffect(foo component) runs, that empty value is shown.
The value is set successfully, and you can check this if you remove the []
array from the Foo component's useEffect. []
means that it will only run once after mounting, acting as componentDidMount.
export default function App() {
const location = useGPS()
useEffect(() => {
console.log(location);
});
return (
<div>1</div>
)
}