Basic react Hooks
2021-04-24
React interview cheatsheet series
Hooks are a new addition in React 16.8. and allows us to write functional programming (with function component) instead of class oriented programming (class components).
The basic hooks are:
- useState(). Which replaces the state of the class component types.
- useEffects(). Which replaces the lifecycle methods like componentDidMount, componentDidUpdate, componentWillUnmount of the class component types.
- useContext(). Which is used in Context API
Another advanced hooks are:
The logic behind useState and useEffect is pretty clear and better adding just a code block that will explain how they work:
1function AddOne() { 2 const [count, setCount] = useState(0); 3 const [title, setTitle] = useState("Please click on the button."); 4 5 // Similar to componentDidMount and componentDidUpdate: 6 useEffect(() => { 7 setTitle(`You clicked ${count} times`); 8 }); 9 10 return ( 11 <> 12 <p>You clicked {count} times</p> 13 Count: {count} 14 <button onClick={() => setCount(count++)}>+1</button> 15 </> 16 ); 17}
####useContext()
About useContext(), accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest <MyContext.Provider> above the calling component in the tree.
This is the offical example at documentation:
1const { useState, useContext } = React 2 3const greetings = { 4 hi: "Hi there!", 5 bye: "Bye bye!" 6}; 7const AppContext = React.createContext(greetings.hi); 8 9 10function Display() { 11 const value = useContext(AppContext); 12 13 return ( 14 <div> 15 <p>{value}</p> 16 </div> 17 ); 18} 19 20const App = () => { 21 return ( 22 <> 23 <AppContext.Provider value={greetings.bye}> 24 <Display /> 25 </AppContext.Provider> 26 </> 27 ); 28}; 29 30ReactDOM.render( 31 <App />, 32 document.getElementById('root') 33);