React Hooks Basics Reference

What are React Hooks?

useState

const [state, setState] = React.useState(initialState)
const [name, setName] = React.useState("Alex Merced")
const [age, setAge] = React.useState(35)

useEffect

React.useEffect(() => {
//This is where stuff would happen the first time a component renders, and anytime any variable passed into the dependency array changes.
return () => {
//The function returned by useEffect only runs when the component is destoryed/removed
}
}, [dependency1, dependency2])

useRef

const MyComponent = (props) => {
const input = useRef(null)
const handleClick = (event) => console.log(input) return (<div>
<input ref={input} value=5/>
<button onClick={handleClick}>Click Me </button>
</div>)
}

useContext

const MyContext = React.createContext(null) //Creates Provider/Consumerconst MyComponent = props => {
const [state, useState] = React.useState(initialState)
return (
<MyContext.Provider value={state}>
<ChildComponent />
</MyContext.Provider>
)
}
import MyContext from "./somefile"const GreatGrandchild = props => {
const greatGrandpasState = React.useContext(MyContext)
return <h1>{greatGrandpasState}</h1>
}

useReducer

const initialState = { count: 1 }const reducer = (state, action) => {
switch (action.type) {
case "add":
return { ...state, count: state.count + action.payload }
break
case "sub":
return { ...state, count: state.count - action.payload }
break
default:
return state
}
}
const MyComponent = props => {
const [state, dispatch] = React.useReducer(reducer, initialState)
return (
<div>
<h1>{state.count}</h1>
<button onClick={() => dispatch({ type: "add", payload: 1 })}>Add</button>
<button onClick={() => dispatch({ type: "sub", payload: 1 })}>
Subtract
</button>
</div>
)
}

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

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