useState
The useState Hook helps you add state to functional components. It takes in an initial value and returns an array with two elements: the current state value and a function to update it. This replaces the need for class components to have a constructor and call the setState method.
Syntax
const [state, setState] = useState(initialState);
Example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useEffect
The useEffect hook in React allows us to perform side effects in our components. It takes in a callback function and an array of dependencies. The callback function is executed after every render, and the dependencies array ensures that the effect is only re-run if any dependencies change. This hook is useful for fetching data, subscribing to events, and performing other side effects in a component's lifecycle.
Syntax
useEffect(() => {
// Side effect logic
return () => {
// Cleanup logic
};
}, [dependencies]);
- No Dependency Array: The effect runs after every render.
- Empty Dependency Array ([]): The effect runs only once after the initial render.
- Dependencies in the Array: The effect runs whenever any of the dependencies change.
1. Running Effect After Every Render
useEffect(()=>{
// Code
})
2. Running Effect Only Once (After Initial Render)
useEffect(()=>{
//Code
},[]) //componentDidMount
3. Running Effect When Dependencies Change
useEffect(()=>{
//Code
},[props]) //componentDidUpdate
Example
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
return () => {
document.title = 'React App';
};
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
useContext
The useContext hook provides a convenient way of consuming data from a React context without having to use the traditional Context.Consumer
component. It accepts a context object as an argument and returns the current context value for that context. This allows us to access context values in any component within the context provider, making it easier to manage the global state.
Syntax
const value = useContext(MyContext);
Example
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#000' : '#fff' }}>
Theme is {theme}
</div>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
}
useRef
The useRef hook allows us to access DOM elements or values that persist between renders in functional components. It returns a mutable ref object that we can use to store any value that persists throughout the component's lifespan. This is useful when we need to access the DOM element directly or store a value that needs to be accessed in different renders.
Syntax
const refContainer = useRef(initialValue);
Example
import React, { useRef, useEffect } from 'react';
function FocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
return <input ref={inputRef} type="text" />;
}
useMemo
The useMemo hook allows us to optimize our application's performance by memoizing a function's result. This means the function will only be re-executed if its dependencies change. This is most useful when dealing with expensive calculations or when the exact value is used multiple times in a component. By using useMemo, we can avoid unnecessary re-rendering and improve our application's overall performance.
Syntax
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
Example
import React, { useMemo } from 'react';
function ExpensiveComponent({ items }) {
const sortedItems = useMemo(() => {
return items.sort((a, b) => a - b);
}, [items]);
return (
<div>
{sortedItems.map(item => <div key={item}>{item}</div>)}
</div>
);
}
useCallback
Only if one of the dependencies has changed does the memoized callback function returned by the useCallback hook alter. This is useful to prevent unnecessary re-renders.
The useCallback Hook is similar to useMemo, but instead of returning a memoized value, it returns a memoized callback function. This is useful when we need to pass a callback to a child component and want to prevent unnecessary re-renders.
Syntax
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
Example
import React, { useState, useCallback } from 'react';
function Button({ onClick }) {
console.log('Button re-rendered');
return <button onClick={onClick}>Click me</button>;
}
function ParentComponent() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
return (
<div>
<Button onClick={increment} />
<p>{count}</p>
</div>
);
}
Conclusion
React Hooks such as useState, useEffect, useContext, useRef, useMemo, and useCallback provide powerful capabilities for managing state, side effects, context, and performance optimizations in functional components. Understanding and utilizing these hooks effectively allows you to create more efficient, readable, and maintainable React applications.
These are the most commonly used React Hooks, but there are more, such as useRef for accessing DOM elements and useReducer for managing complex states. React Hooks provides a more intuitive and concise way of writing React code, improving code readability and maintainability. They also eliminate the need for higher-order components and render props, making code easier to understand for beginners. Our reactjs developers are aware of using hooks in React development services roughly. So, next time you start a new React project, consider using Hooks to improve your project's flexibility or hire an expert React development team from Elightwalk Technology.
Top comments (0)