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 new folder called ‘effects’ then a file with the name of your custom hook with the ‘use’ keyword. E.g. ‘useFetch’.
  2. Create your custom hook. E.g.
  • Create the context using createContext
  • 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).

--

--

--

Social Entrepreneur and Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Use Twitch to Login to Your Chrome Extension

Offline POSTs with Progressive Web Apps

Reversing a Linked List

Setting up a REST API using Express

Compress Multiple Image using Windows Resizer and Image Magick Linux

Using ReactJS Routes (TheRock fan club App)

START!

Create a Sliding React Navigation Bar

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
Felipe Bohorquez

Felipe Bohorquez

Social Entrepreneur and Software Engineer

More from Medium

React, ViteJS, TypeScript, and Jest

React Hooks: useReducer

React Hooks

What is React Hooks?