What are ReactJS hooks? How can they be useful?
ReactJS hooks are a powerful tool for building dynamic and interactive web applications.
They were introduced in React 16.8, and they allow developers to use state and other React features in functional components without writing classes, making code simpler and more efficient.
The most commonly used built-in hooks include useState, useEffect, and useContext.
useState hook: It is used to add state to a functional component. It takes an initial state as a parameter and returns a state variable and a function to update the state. Here is an example:
import React, { useState } from 'react'; | |
function Example() { | |
const [count, setCount] = useState(0); | |
return ( | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => setCount(count + 1)}> | |
Click me | |
</button> | |
</div> | |
); | |
} |
useEffect hook: It is used to handle side effects, such as fetching data from an API or updating the document title. It takes a function to run after the component renders and an optional array of dependencies. Here is an example:
import React, { useState, useEffect } from 'react'; | |
function Example() { | |
const [data, setData] = useState(null); | |
useEffect(() => { | |
async function fetchData() { | |
const result = await fetch('/api/data'); | |
const data = await result.json(); | |
setData(data); | |
} | |
fetchData(); | |
}, []); | |
if (data) { | |
return <div>{data}</div>; | |
} else { | |
return <div>Loading...</div>; | |
} | |
} |
useContext hook: It is used to access context in a functional component. It takes a context object created by the createContext function and returns its value. Here is an example:
import React, { useContext } from 'react'; | |
const ThemeContext = React.createContext('light'); | |
function ThemeButton() { | |
const theme = useContext(ThemeContext); | |
return <button style={{ background: theme.background, color: theme.foreground }}>I am styled by theme context!</button>; | |
} |
By taking the time to understand and use React hooks, developers can create better web applications that are easier to maintain over time.
Comments
Post a Comment