Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 1, 2021 03:33 am GMT

React Hooks Notes

Motivation

Building a simple table of reference for the forgetful
Based on:

HookUsage
useStateconst [count, setCount] = useState(0);
useEffectuseEffect(() => {
console.log("run when mounted & when state changes")
})

useEffect(() => {
console.log("run once when mounted")
},[])

useEffect(() => {
console.log("run when state changes")
},[state])

useEffect(() => {
console.log("set tear down function");
return () => console.log("run when tear down");
})
useContext// share data without passing props
// create
const data = {state:'happy'}
const DataContext = createContext(data);

// wrap
const App = () => {
<DataContext.Provider value={data.state}>
<ChildComponent />
</DataContext.Provider>
}

// use
const ChildComponent = () => {
const data = useContext(DataContext);
return <p>{state}</p>;
}
useRef// for mutable state that does not re-render UI
const count = useRef(0);

// for element from the DOM
const myBtn = useRef(null);
const click = () => myBtn.current.click();
return (<button ref={myBtn}></button>);
useReducer// dispatch actions to reducer function
const reducer = (state, action) => {
if (action.type === 'increment') { // or switch
return state + 1;}
}

const [state, dispatch] = useReducer(reducer, 0);

return (
<button onClick={() => dispatch({type: 'increment'})}>+</button>
);
useMemo// for expensive computation to get return values
useMemo(() => {
return count ** 2; // expensive
}, [count]) // recompute when count changes
useCallback// for functions
const showCount = useCallback(() => {
console.log(change only when ${count} changes\);
}, [count])

return (
<div handler = {showCount}></div>;
)

Original Link: https://dev.to/tlylt/react-hooks-notes-o0g

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To