Hooks: The Hero of React
React is a front-end JavaScript framework.
While building HTML pages and managing them can become tedious, React makes
things easier by breaking on-screen elements and their logic down into
components.
React brings a lot to the table, but one of the
most useful features is state management. In this article, you'll learn how to
manage state using React Hooks. Before proceeding further, this article assumes
you know the basics of React.
What Are Hooks in ReactJS?
The hook is a new concept introduced in React
for managing state and other features of React.
By using hooks in React, you can avoid writing lengthy code that would
otherwise use classes. The following example demonstrates an example of the useState hook.
const [variable, setVariable] = useState(initial value);
Here the variable is
the state and the setVariable is
the function that sets the state. useState is
the hook that holds the initial value of the state variable. Don't worry if
this doesn't make any sense to you. By the end of this tutorial, you'll have a
solid grasp on hooks.
There are two types of hooks:
- Basic
Hooks
a.
useState
b.
useEffect
c.
useContext
- Additional
Hooks
. useRef
a.
useMemo
b.
useReducer
useState()
The useState hook
helps manage state. Earlier on in React development, state management was done
using classes. The state syntax was written inside the constructor and used the this keyword. With the
introduction of React hooks, developers have the liberty to manage state using
functional components.
You can refer to the previous example for the
syntax of React hooks. The simplest example to explain useState() is the count
variable example:
import {useState} from "react";
function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<h1>Hooks example</h1>
<h1>{count}</h1>
<button onClick={()=>setCount(count+1)}>Add</button>
<button onClick={()=>setCount(count-1)}>Subtract</button>
</div>
);
}
The useState hook
has a variable and method that's used to set the value of the variable. The useState hook accepts the
initial value of the state as the parameter. You can set any value for the
count variable using the setCount method.
There are two buttons in the above code to
increment and decrement the value of the count variable.
While incrementing, you can add +1 to the current count state and -1 to
decrement the count by 1.
useEffect
The useEffect hook
updates the state on the web page after every change in state. The useEffect hook was
introduced to remove the side-effects of class-based components. Before the
introduction of function-based components, changes in state were tracked using
the lifecycle components: componentDidMount and componentDidUpdate. The useEffect hook accepts a
dependency array. All changes in the state variables mentioned in the
dependency array are tracked and displayed using the useEffect hook.
A classic example of using the useEffect hook is fetching data from an API or calculating the likes or
subscriptions on a post.
useEffect(()=>{
// code
},[dependency array]);
Considering the above example
import { useState, useEffect } from "react";
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You have clicked for ${count} times`;
}, [count]);
return (
<div className="App">
<h1>Hooks example</h1>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Add</button>
</div>
);
}
On passing the count state
variable in the useEffect dependency
array, it checks whether the state has changed or not. It then sets the
document title to the count variable.
useContext
The useContext hook
helps pass data through the component without doing it manually via props. It
makes using the Context API quick and easy. You'll have a better understanding
after running through an example.
First, understand how the code looks without
using Context. As you can see, you have to pass the text via props to the child
component. To avoid complexities, you can use the useContext hook.
export default function App() {
let text = "Hello, Welcome to MUO";
return (
<div className="App">
<ChildComponent text={text} />
</div>
);
}
const ChildComponent = ({ text }) => {
return <div>{text}</div>;
};
Firstly, create a Provider in your main file (App.js).
const Context = React.createContext(null);
The App component
is the top-level component or "parent" component. You need to wrap
the entire component in the <Context.Provider> and
pass the object or data you want to render on the child component.
export default function App() {
let text = "Hello, Welcome to MUO";
return (
<Context.Provider value={text}>
<div className="App">
<ChildComponent />
</div>
</Context.Provider>
);
}
Now, create a child component and access the
text prop using the useContext hook.
Pass the Context variable using createContext.
const ChildComponent = () => {
let text = useContext(Context);
console.log(text);
return <h1>{text}</h1>;
};
A Lot More to Explore With
React
You just learned the basics of hooks. It's one
of the best features of React, and pretty developer-friendly, too. React is one
of the best frontend frameworks to learn today for job opportunities, creating
single-page apps, or simply to broaden your programming knowledge.
Speaking of broadening your knowledge, managing
state is only one skill that React developers need to practice. Other key
features, such as props, deserve just as much of your attention.