As the ReactJs library gets new updates, there are a lot of things being added and a few that are deprecated too. ReactJs is becoming more powerful day by day due to such updates. As a developer, you need to keep yourself up to date with new features coming out in every version.
Well, React Hooks, a feature which is available in React v16.7.0-alpha, is something awesome you should know about.
$ npm install [email protected] --save
$ npm install [email protected] --save
Hooks in React.
useState
useEffect
useContext
useReducer
useCallback
useMemo
useRef
useImperativeMethods
useMutationEffect
Note: currently identical touseEffect
useLayoutEffect
Note: currently identical touseEffect
This example renders a counter. When you click the button, it increments the value:
import { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
You can use the State Hook more than once in a single component:
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
// ...
}
The Effect Hook, useEffect
, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount
, componentDidUpdate
, and componentWillUnmount
in React classes, but unified into a single API.
For example, this component sets the document title after React updates the DOM:
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
To use hooks in a functional component!
import React, { useState, useEffect, useReducer, memo } from 'react';
const style = {
height: 60,
width: 50,
margin: 10,
}
function reducer(state, action) {
switch (action.type) {
case 'reset':
return { count: action.payload };
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
// A reducer must always return a valid state.
// Alternatively you can throw an error if an invalid action is dispatched.
return state;
}
}
function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, initialState, { type: 'reset', payload: initialCount });
return (
<div>
<p style={{ fontSize: 100 }}><b>{state.count}</b></p>
<button style={style} onClick={() => dispatch({ type: 'reset', payload: initialCount })}>
Reset
</button>
<button style={style} onClick={() => dispatch({ type: 'increment' })}>
β
</button>
<button style={style} onClick={() => dispatch({ type: 'decrement' })}>
β
</button>
</div>
);
}
const MyComponentMemo = memo((props) =>{
return (
<>
<div style={{ fontSize: 50 }}>{props.name}</div>
</>
)
});
function MyComponent() {
const [name, setName] = useState('π');
return (
<div className="App">
<header className="App-header">
<div>
<br />
<input type="text" onChange={(e) => setName(e.target.value)} />
<MyComponentMemo name={name} />
{Counter({ initialCount: 0 })}
</div>
</header>
</div >
);
}
Hooks are JavaScript functions, but they have two additional rules:
- Note: Only call Hooks at the top level. Donβt try to call Hooks inside loops, conditions, or nested functions.
- Note: Only call Hooks from React function components. Donβt try to call Hooks from regular JavaScript functions.
React Hooks API here: https://reactjs.org/docs/hooks-reference.html
Check out contribution guidelines πCONTRIBUTING.md
MIT License
Copyright (c) 2018 Asif Vora
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.