React all hook example- useState: Allows functional components to manage local state.
- useEffect: Performs side effects in function components, similar to componentDidMount and componentDidUpdate in class components.
- useContext: Accepts a context object and returns the current context value for that context.
- useReducer: Alternative to useState. Accepts a reducer of type (state, action) => newState, and returns the current state paired with a dispatch method.
- useCallback: Returns a memoized callback.
- useMemo: Returns a memoized value.
- useRef: Returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
- useLayoutEffect: The signature is identical to useEffect, but it fires synchronously after all DOM mutations.
- useImperativeHandle: Customizes the instance value that is exposed when using ref.
- useDebugValue: Used to display a label for custom hooks in React DevTools
Certainly! Here's a simple example of how you can use the useReducer
hook in React:
import React, { useReducer } from 'react'; // Initial state const initialState = { count: 0 }; // Reducer function const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; case 'reset': return initialState; default: throw new Error(); } }; // Component const Counter = () => { // useReducer hook const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <h2>Count: {state.count}</h2> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> <button onClick={() => dispatch({ type: 'reset' })}>Reset</button> </div> ); }; export default Counter;
In this example:
- We define an initial state object (
initialState
) with a single propertycount
. - We define a reducer function (
reducer
) that takes the current state and an action, and returns the new state based on the action type. - In the
Counter
component, we use theuseReducer
hook, passing in the reducer function and the initial state. - Inside the component, we have buttons for incrementing, decrementing, and resetting the count. Each button click dispatches an action to the reducer, which updates the state accordingly.
This is a basic example, but it demonstrates the fundamental concepts of using useReducer
in React. Let me know if you need further clarification or assistance!