1. useState
useState
is the cornerstone of React hooks, enabling components
to manage state locally. Here's a basic example:
import React, { useState } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Add 1 to count</button>
</div>
);
};
2. useEffect
useEffect
allows performing side effects in function components.
It runs after the component renders and after every update.
import React, { useEffect, useState } from "react";
const Example = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log("Component mounted or count updated");
}, [count]);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment Count</button>
</div>
);
};
3. useRef
useRef
provides a way to persist mutable values across renders
without triggering a re-render.
import React, { useRef } from "react";
const TextInput = () => {
const inputRef = useRef();
return (
<input
ref={inputRef}
onChange={() => {
console.log(inputRef.current.value);
}}
/>
);
};
4. useMemo
useMemo
memoizes expensive computations and recalculates only
when dependencies change.
import React, { useState, useMemo } from "react";
const MemoExample = () => {
const [apiURL, setApiURL] = useState("https://callAPI/");
const apiResults = useMemo(() => {
// Perform heavy computations or API calls
console.log("API call made");
}, [apiURL]);
return (
<div>
<button onClick={() => setApiURL("https://dummyAPI")}>Change API Url</button>
</div>
);
};
5. useCallback
useCallback
memoizes functions to prevent unnecessary renders in
child components.
import React, { useState, useCallback } from "react";
const CallbackExample = () => {
const [value, setValue] = useState("");
const handleChange = useCallback((event) => {
setValue(event.target.value);
}, []);
return (
<div>
<input value={value} onChange={handleChange} />
</div>
);
};
6. useContext
useContext
provides a way to pass data through the component tree
without manually passing props at every level.
import React, { useState, useContext, createContext } from "react";
const ThemeContext = createContext();
const App = () => {
const [darkTheme, setDarkTheme] = useState(false);
return (
<ThemeContext.Provider value={darkTheme}>
<button onClick={() => setDarkTheme(!darkTheme)}>Toggle Theme</button>
<AboutPage />
</ThemeContext.Provider>
);
};
const AboutPage = () => {
const darkTheme = useContext(ThemeContext);
return (
<div style={{ backgroundColor: darkTheme ? "black" : "white" }}>
{/* Content here */}
</div>
);
};
7. useReducer
useReducer
is preferable for managing state logic that involves
multiple sub-values or when the next state depends on the previous one.
import React, { useReducer } from "react";
const initialState = { count: 0 };
const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
};
const Counter = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h1>{state.count}</h1>
<button onClick={() => dispatch({ type: "increment" })}>Increment</button>
<button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>
</div>
);
};
8. useLayoutEffect
useLayoutEffect
is similar to useEffect
, but it runs
synchronously after all DOM mutations. Use with caution due to potential
performance implications.
import React, { useLayoutEffect } from "react";
const LayoutEffectExample = () => {
useLayoutEffect(() => {
console.log("Component is about to update");
}, []);
return <div>Example using useLayoutEffect</div>;
};
By understanding these popular React hooks, you can enhance the functionality and efficiency of your React applications. Experiment with these examples to grasp their full potential and improve your development workflow.
That's it for this topic. Thank you for reading!