React & React Native Hooks
In #React and #ReactNative, #hooks are a powerful feature that allows developers to use state and other React features in functional components without having to use class components or render props. Hooks were introduced in React version 16.8 and have become a popular way to manage state and lifecycle methods in React applications.
There are several built-in hooks provided by React and developers can also create their own custom hooks to reuse logic across components. Here are some of the most commonly used built-in hooks in React:
The useState hook is used to manage state in functional components. It takes an initial state value as a parameter and returns an array with two elements: the current state value and a function to update the state.
Here's an 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> );
}
In this example, the useState hook is used to create a count state variable and a setCount function to update it. The state variable is initialized to 0.
2. #useEffect
The useEffect hook is used to perform side effects in functional components. It takes a function as a parameter and runs it after every render. This hook is commonly used to fetch data from an API, update the title of the page, or add event listeners.
Here's an example:
import React, { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return ( <div>
<p>Seconds: {seconds}</p>
</div> )
}
In this example, the useEffect hook is used to create a timer that increments the seconds state variable every second. The setInterval function returns an ID that is used to clear the interval when the component unmounts.
3. #useContext
The useContext hook is used to consume a context created by the React.createContext() function. It takes a context object as a parameter and returns the current value of that context.
Here's an example:
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Header() {
const theme = useContext(ThemeContext);
return ( <div style={{ backgroundColor: theme.background, color: theme.foreground }}>
<h1>Header</h1>
</div> ) }
In this example, the useContext hook is used to consume the ThemeContext context created by the React.createContext() function. The theme variable contains the current value of the context.
4. #useRef
The useRef hook is used to create a mutable reference that persists between renders of a component. This can be useful for storing references to DOM elements, managing focus, or keeping track of other mutable values.
Here's an example:
import React, { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return ( <div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Focus</button>
</div> )
}
In this example, the useRef hook is used to create a reference to the input element. The handleClick function is called when the button is clicked, which uses the current property of the inputRef to focus the input element.
5. #useMemo
The useMemo hook is used to memoize the result of a function call, so that it is only re-computed when its dependencies change. This can be useful for expensive calculations or functions that are called frequently.
Here's an example:
import React, { useMemo } from 'react';
function ExpensiveCalculation({ a, b }) {
const result = useMemo(() => {
// perform an expensive calculation
console.log('Performing an expensive calculation');
return a * b; }, [a, b]);
return ( <div> Result: {result} </div> ); }
In this example, the useMemo hook is used to memoize the result of an expensive calculation. The function is only re-computed when the a or b dependencies change, which helps to optimize performance.
6. #useCallback
The useCallback hook is used to memoize a function, so that it is only re-created when its dependencies change. This can be useful for preventing unnecessary re-renders of child components that depend on the function.
Recommended by LinkedIn
Here's an example:
import React, { useCallback, useState } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => { console.log('Clicked');
}, []);
return ( <div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}> Click me </button>
<ChildComponent onClick={handleClick} />
</div> )
}
In this example, the useCallback hook is used to memoize the handleClick function, which is passed down to a child component as a prop. The function is only re-created when the count dependency changes, which helps to optimize performance by preventing unnecessary re-renders of the child component.
7. #useReducer
The useReducer hook is used to manage state in a more complex manner than useState hook. It is used to handle state transitions that involve more than one value or complex state logic.
Here's an example:
import React, { useReducer } from 'react';
const initialState = { count: 0, };
function reducer(state, action) {
switch (action.type)
{
case 'increment':
return {
count: state.count + 1
};
case 'decrement':
return { count: state.count - 1 };
default: throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return ( <div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment </button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement </button> </div> )
}
In this example, the useReducer hook is used to manage the count state of the Counter component. The reducer function takes the current state and an action object as arguments, and returns a new state based on the action type. The dispatch function is used to trigger state transitions by passing an action object to the reducer function.
The useImperativeHandle hook is used to expose custom imperative methods to parent components. It is useful for cases where a child component needs to expose certain functionality to the parent component.
Here's an example:
import React, { useRef, useImperativeHandle } from 'react';
function ChildComponent(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
},
}));
return <input type="text" ref={inputRef} />;
}
ChildComponent = React.forwardRef(ChildComponent);
function ParentComponent() {
const childRef = useRef(null);
const handleClick = () => {
childRef.current.focusInput();
};
return ( <div>
<ChildComponent ref={childRef} />
<button onClick={handleClick}>Focus Input</button>
</div> );
}
In this example, the useImperativeHandle hook is used to expose a focusInput method to the parent component, which can be used to focus the child component's input element. The ref argument is used to forward the focusInput method from the child component to the parent component.
The useLayoutEffect hook is similar to useEffect, but it is executed synchronously after all DOM mutations. It is useful for cases where you need to perform some action after the DOM has been updated.
Here's an example:
import React, { useState, useLayoutEffect } from 'react';
function Example() {
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
const handleResize = () => {
setWidth(window.innerWidth);
};
window.addEventListener('resize', handleResize); handleResize();
return () => {
window.removeEventListener('resize', handleResize); };
}, []);
return <div>Window width: {width}</div>;
}
In this example, the useLayoutEffect hook is used to set the width state
10. #useDebugValue
The useDebugValue hook is used to display a label for custom hooks in React DevTools. It is useful for cases where you want to provide additional information about a custom hook.
Here's an example:
import { useDebugValue } from 'react';
function useCustomHook() {
const value = 'Hello, world!';
useDebugValue(value);
return value;
}
function Component() {
const value = useCustomHook();
return <div>{value}</div>;
}
In this example, the useCustomHook hook uses useDebugValue to display a label for the hook in React DevTools. The Component component uses the useCustomHook hook to get the value and display it in a div.
The useReducer hook can also be used in conjunction with useContext. This is useful for cases where you need to manage state at a higher level in the component tree.
Here's an example:
import React, { createContext, useContext, useReducer } from 'react';
const initialState = { count: 0, };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default: throw new Error();
}
}
const MyContext = createContext();
function ChildComponent() {
const { state, dispatch } = useContext(MyContext);
return ( <div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Increment
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Decrement
</button>
</div> ); }
function ParentComponent() {
const [state, dispatch] = useReducer(reducer, initialState);
return ( <MyContext.Provider value={{ state, dispatch }}>
<ChildComponent />
</MyContext.Provider>
);
}
In this example, the useReducer hook is used to manage the count state at the ParentComponent level. The MyContext.Provider component is used to pass down the state and dispatch values to the ChildComponent, where they are consumed using the useContext hook. The ChildComponent displays the count value and provides buttons to increment and decrement it using the dispatch function.
This is an insightful post! React has become a popular choice for managing complex UIs, and React Native has opened up opportunities for cross-platform mobile app development. The declarative nature of React allows for efficient component-based development, making it easier to build and maintain large-scale applications. With React Native, we can leverage our existing React knowledge to create native mobile experiences. It's incredible how React's ecosystem continues to evolve and empower developers. Thanks for sharing your thoughts on React management and React Native! For more information visit https://www.garudax.id/feed/update/urn:li:activity:7071838923370418176
Hello MUNEM... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any
Hello MUNEM... We post 100's of job opportunities for developers daily here. Candidates can talk to HRs directly. Feel free to share it with your network. Visit this link - https://jobs.hulkhire.com And start applying.. Will be happy to address your concerns, if any