当前位置:网站首页>Usestate vs useref and usereducer: similarities, differences and use cases

Usestate vs useref and usereducer: similarities, differences and use cases

2022-06-23 15:27:00 Code Taoist

This article explains React Hooks —— useStateuseRef and useReducer The similarities and differences of , You will learn about their basic usage and different use cases .

Have a look first Hook The rules of

  • Hooks Only from React Top level calls to functions
  • You cannot start from nested code ( For example, circulation 、 Conditions ) Call in hook
  • You can also customize Hooks Called from the top level of Hooks

Usually , Should call unconditionally hook:)

understand useState hook

useStateHook You can develop component states for functional components .

Take a look at the code below .

import { useState } from "react";
function AppDemo1() {
  const [darkMode,darkModeUpdater]= useState(true);
 
  return (
    <div>
      <p>{darkMode ? "dark mode on" : "dark mode off"}</p>
      <button onClick={() => darkModeUpdater(!darkMode)}>
        toggle dark mode
      </button>
    </div>
  );
}

useState Hook Returns an array containing two items . In the example , We implemented a Boolean component state , And use true It's initialized ,

Single parameter useState Only considered during the initial render cycle . Update... With the second value ,useState You can handle data types from numbers to Booleans to objects , It can even be a callback function , Return value after calculation , If you want to expand the calculation when the component is rendered for the first time , It would be useful .

In the following cases , We would prefer to use useState

  1. If we need to re render after the state variable changes
  2. Simple state with simple updates and use cases —— If the state becomes complex or we have different ways to update the State , We should consider using useReducer hook

understand useRef hook

useRef hook and useState hook be similar , But it is different in the following cases :

In the following cases , We would prefer to use useRef

  1. Updated values should not be re rendered UI, Otherwise we should use useState /useReducer hook
  2. When we want direct access to React Component or HTML Element time
  3. We can use it as a persistent store of data in the current attribute

Be careful : Change during rendering ref, That is, from places other than those just mentioned , Errors may be introduced . This also applies to useState.

Take a look at the code below .

import { useEffect, useState, useRef } from "react";

const AppDemo13 = () => {
 
  const [count, setCount] = useState(0);
  // Get the previous value (was passed into hook on last render)
  const ref = useRef();
  // Store current value in ref
  useEffect(() => {
    console.log("useEffect");
    ref.current = count;
  }, [count]); // Only re-run if value changes (kind of Component did update)
  return (
    <div className="App">
      <h1>
        Now: {count}, before: {ref.current}
      </h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

understand useReducer hook

When you have complex state logic involving multiple sub values or the next state depends on the previous state ,useReducer Often than useState A more useful .

Take a look at the code below .

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:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}

If you work on a single state and have various schedulers to change the State , This method will teach us to understand redux In a logical way .

Conclusion

  1. When the state to be managed is simple enough , Consider using useState
  2. When we have complex logic and reliable states for various actions , Use useReducer
  3. useRef Store and persist the re rendered data and access it directly DOM Elements , If you want to improve the performance of controlled input elements , We can use useRef To reduce the amount of re rendering per keystroke .
原网站

版权声明
本文为[Code Taoist]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231336145595.html