1. useState
UseState takes a parameter (the initial value of the state)
UseState return value: an array first item: state value second item: method to modify state
import { useState } from "react";
function Demo1() {
// Define the initial count value
const initCount = 0;
const [count, setCount] = useState(initCount);
const increment = (a)= > {
setCount((count) = > count + 1);
// The count printed here is not the latest, but the last count. Why?
console.log(count);
};
return (
<div>
<h3>{count}</h3>
<button onClick={()= > setCount(count + 1)}>count++</button>
<button onClick={increment}>count++</button>
</div>
);
}
export default Demo1;
Copy the code
React generates a useState function for each state update, so the latest update can only get the state value that was updated last time. To get the latest state value, you need to use the next hook (useEffect). Keep reading…
2. useEffect
UseEffect corresponds to the three life cycles of a class component, which are:
(componentDidMount, componentDidUpdate, componentWillUnmount)
import { useEffect, useState } from "react";
function Demo2() {
const initCount = 0;
const initName = "kyrie";
const [count, setCount] = useState(initCount);
const [name, setName] = useState(initName);
const increment = (a)= > {
setCount((count) = > count + 1);
};
const changeName = (a)= > {
setName("wen");
};
// componentDidUpdate - Call timing: All status updates are called
useEffect((a)= > {
// console.log(count, "count");
});
// componentDidUpdate - Call timing: dependent status updates are called (i.e., the state value passed in for the second argument (array))
useEffect((a)= > {
// Only called when count changes
console.log(count, "count"); // 1 2 3 4 5... This is where you get the latest count
}, [count]);
useEffect((a)= > {
// Only called when count changes
console.log(name, "name"); // wen name
}, [name]);
useEffect((a)= > {
// If count or name changes, multiple states can be passed in
console.log(count, "count"); // 1 2 3 4 5...
console.log(name, "name"); // wen name
}, [count, name]);
// componentDidMount - Call timing: called once during initialization, not later
useEffect((a)= > {
console.log(count, "count");
} []);
// componentWillUnmount - Call timing: called when the component is destroyed
useEffect((a)= > {
console.log("useEffect");
// The returned function is called when the component is destroyed
return (a)= > {
console.log("Component destroyed");
};
});
return (
<div>
<h3>{count}</h3>
<h3>{name}</h3>
<button onClick={increment}>count++</button>
<button onClick={changeName}>changeName</button>
</div>
);
}
export default Demo2;
Copy the code
3. useRef
UseRef receives an initial value and returns an object with a current attribute {current:… }
The value of the current property is the real-time status value
import { useRef } from "react";
const inputRef = useRef(null);
<input ref={inputRef} type="text" />
// inputref. current gets the DOM element of the input box
<button onClick={()= >Inputref.current. Focus ()}> Click focus</button>
Copy the code
4. useContext
UseContext must work with createContext
import { useContext, createContext } from "react";
// Create a context
const myContext = createContext();
// The provider value is passed through it
const { Provider } = myContext;
const [theme, setTheme] = useState({ background: "white".color: "black" });
function toggleTheme() {
theme.background === "white"
? setTheme({ background: "black".color: "white" })
: setTheme({ background: "white".color: "black" });
}
/ / the parent component
// The values that need to be passed to descendant components are put into the value property
<Provider value={{ theme, toggleTheme }}>
<Child />
</Provider>
// child components
// Child components can get passed values (including methods) from the parent component's context
const { theme, toggleTheme } = useContext(myContext);
return (
<div>
< h2 > Child component < /h2>
<button
style={{ background: theme.background.color: theme.color }}
onClick={()= > toggleTheme(theme)}
>
To switch the color
</button>
</div>
);
Copy the code
5. UseReducer (Redux’s Idea)
The useReducer receives two parameters, the first is the Reducer function and the second is the initial state
UseReducer return value: the first item is store (i.e. collection of shared states) and the second item is dispatch (method of changing the state)
import { useReducer } from "react";
// Define a reducer function
function reducer(state, action) {
switch (action.type) {
case "increment":
return {
num: state.num + action.count
};
case "decrement":
return {
num: state.num - action.count
};
default:
return state;
}
}
const [store, dispatch] = useReducer(reducer, { num: 100 });
<h3>Num: {store. Num}</h3>
<button onClick={()= > dispatch({ type: "increment", count: 100 })}>+</button>
<button onClick={()= > dispatch({ type: "decrement", count: 100 })}>-</button>
Copy the code
6. Custom hooks
// customize a count++ hooks function for easy reuse and more semantic hooks names
function useCount(initCount) {
const [count, setCount] = useState(initCount);
return [
count,
() = > {
setCount((count) = > count + 1);
}
];
}
const [count, addCount] = useCount(0);
<button onClick={()= > {addCount()}> + </button>
Copy the code
This article belongs to the basic content, in fact, there are hooks to further use, and I will write a separate article about the further use of useEffect for you to learn. I believe that after reading this article, you will understand it better when you read the further use of useEffect.