React Hooks: Going Beyond useState

// mimics as a render lifecycle method

useEffect(() => {
console.log('hello')
})

// ...assume this code on an input
onChange={e => setQuery(e.target.value)}

// useEffect gets called whenever onChange changes value
useEffect(() => {
console.log('hello')
},[])
useEffect(() => {
if (query.length > 0) {
const fetchUser = async () => {
const res = await fetch('baseURL')
const resJson = await res.json()
//useState call
setUser(resJson)
}

fetchUser()
}
},[query])
// behaves like componentDidMount avoids missing dependency warning
useEffect(() => {
checkUserSession()
}, [checkUserSession])
//ComponentDidMount
//Class
componentDidMount() {
console.log('I just mounted!');
}

//Hooks
useEffect(() => {
console.log('I just mounted!');
}, [])


//ComponentWillUnmount
//Class
componentWillUnmount() {
console.log('I am unmounting');
}

//Hooks
useEffect(() => {
return () => console.log('I am unmounting');
}, [])


// ComponentWillReceiveProps
//Class
componentWillReceiveProps(nextProps) {
if (nextProps.count !== this.props.count) {
console.log('count changed', nextProps.count);
}
}

//Hooks
useEffect(() => {
console.log('count changed', props.count);
}, [props.count])
  1. Create your custom hook. E.g.
  • Import the context you created and also the useContext library. Pass in the context created to useContext as your context. E.g. const myContext = useContext(sampleContext).

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store