5 min to read
In 2018, at the React Conference “Hooks” was officially introduced to React. Hooks arrived as a savior for developers who were struggling in maintaining hundreds of states for hundreds of components.
They let you use state and other React features without writing a class. Now, you can kick out classes from your components.
No need to worry, There are no plans to remove classes from React permanently, yet
You can adapt Hooks gradually, Hooks work side-by-side with existing code so there is no rush to migrate to Hooks. You don’t have to learn or use Hooks right now if you don’t want to.
You might be thinking about why you need to learn one more feature. The answer is here:
Class Components
class Clock extends React.Component {
...
...
render() {
return (
<div>
<h1>...something...</h1>
</div>
);
}
}
Function Components
function Example() {
... // Hooks can be used here
...
render() {
return (
<div>
<h1>...something...</h1>
</div>
);
}
}
function Example = () => {
... // Hooks can be used here
...
render() {
return (
<div>
<h1>...something...</h1>
</div>
);
}
}
> you can also pass props to the function:
function Example(props) {
... // Hooks can be used here
...
}
function Example = (props) => {
... // Hooks can be used here
...
}
props can be accessed like this -> const v = props.value
const state = {
x: 10,
y: 'hello',
z: {
word: "world!"
}
}
useState is used to set the initial value for a local state.
// this is How we declare a new state variable
const [color, setColor] = useState('Yellow');
// declaring multiple state variables
const [x, setX] = useState(10);
const [y, setY] = useState('hello');
const [z, setZ] = useState([{
word: "world!",
}]);
this
constructor(props) {
this.state = { text: 'demo' };
}
render() {
return (
<div>
<h1>This is { this.state.text }</h1>
</div>
);
}
While using hooks, state variables can be accessed directly
const [text, setText] = useState('demo');
render() {
return (
<div>
<h1>This is { text }</h1>
</div>
);
}
...
this.state = {
a: 1,
b: 2,
fruit: 'apple'
}
...
{
this.setState({
...state,
fruit: 'orange'
});
}
const [fruit, setFruit] = useState('apple');
...
{
setFruit('orange')
}
// To run with each Update
useEffect(() => {
// Do something
});
// run only when value of "color" is changed
useEffect(() => {
// Do something
}, [color]);
// run only on first render
useEffect(() => {
// Do something
}, []);
Let’s see some usages, in lifecycle methods
— ComponentDidMount
componentDidMount() {
// do something
const cat = "tom";
this.setState({
...state,
animal: cat
});
}
useEffect(() => {
// Do Something
const cat = "tom";
setAnimal(cat);
}, []);
— ComponentDidUpdate
componentDidUpdate() {
// do something
const cat = "tom";
this.setState({
...state,
animal: cat
});
}
useEffect(() => {
// Do Something
const cat = "tom";
setAnimal(cat);
})
The above snippet will run the code at every update including the first render acting as a combination of componentDidMount and componentDidUpdate, if you want to prevent it from running on the first render, then it can be done by keeping a check of first render, like this:
const [isFirstRender, setIsFirstRender] = useState(true);
useEffect(() => {
if (isFirstRender) {
setIsFirstRender(false);
} else {
// do Something
const cat = "tom";
setAnimal(cat);
}
}
— ComponentWillUnmount
componentWillUnmount() {
// Do Something
}
Just return a function ( named or anonymous ) for cleanup, that we do in ComponentWillUnmount
useEffect(() => {
return () => {
// Do something
}
});
useContext()
takes a context object as the parameter and returns the corresponding context values at that time. Refer to the example below for a better understanding.
// for example, We have
const flowers = {
sunflower: {
petals: 25,
color: "yellow"
},
daisy: {
petals: 5,
color: "white"
},
rose: {
petals: 30,
color: red
}
};
// Creating our context
const MyContext = React.createContext( flowers.rose );
// Wrappin the component with <MyContext.Provider>
function App() {
return (
<MyContext.Provider value={ flowers.sunflower }>
<MyComponent />
</MyContext.Provider>
)
}
The current context value is determined by the value of the value
prop passed in the nearest <MyContext.Provider>
in which the component is wrapped.
// ... somewhere in our function component ...
const flower = useContext(MyContext);
Now the flower will have the value of a rose:{ petals: 30, color: "red" }
and can be used as<p>Colour of rose is { flower.color }.</p>
It will run each time when the context is updated
You must have got the ‘context‘ of this blog if you are still here, kindly have a look at “Some rules to remember” below:
Some other commonly used Hooks are:
A custom Hook is a function whose name starts with ”use
” and that may call other Hooks and, lets you extract component logic into reusable functions.
Let’s create a custom Hook useColor
that returns the color of the flower whose ID is passed as an argument:
function useColor(flowerID) {
const [color, setColor] = useColor(null);
useEffect(() => {
/* Extract the value of colour of the flower from the database and set the value of color using setColor() */
});
return color;
}
Now, we can use our custom hook,
{
// To get the colour of the flower with ID = 10
const color = useColor(10);
}
Learn more about how to create custom hooks in detail.
See official docs for React Hooks.
Tags
Are you looking for something specific?
We understand that hiring is a complex process, let’s get on a quick call.
Share
11 comments