In react components, when there is logic that can be shared between components, the common logic is reused in the way of higher-order components. In React function components, Hook provides a customized hook function scheme to reuse the common logic.
The following illustrates the basic usage of custom hooks by creating a reuse example of value and onChange methods in a form controlled component.
The code is as follows:
import React, { useState } from 'react';
// Customize hook(start with use)
// Reuse controlled forms to create state and onChange method logic
/ * * * *@param {string | number} InitialValue Indicates the initial default value *@returns * /
const useInput = (initialValue) = > {
const [value, setValue] = useState(initialValue)
return {
value,
onChange: e= > setValue(e.target.value)
}
}
// Form component
const FormComponent = () = > {
const username = useInput('admin')
const password = useInput(' ')
const onSubmit = (e) = > {
e.preventDefault()
// Get the form value
console.log(username.value, password.value);
}
return (
<form onSubmit={onSubmit} >
<input type="text" {. username} / >
<input type="password" {. password} / >
<button type="submit">submit</button>
</form>
);
}
export default FormComponent;
Copy the code
The methods that request data in many components can also be encapsulated as custom hook functions that can be shared by multiple components.
The code is as follows:
import React, { useEffect, useState } from 'react';
import axios from 'axios'
// Custom hook
// Encapsulate common request logic and return data
const usePosts = () = > {
const [posts, setPosts] = useState(' ')
useEffect(() = > {
getPosts()
}, [])
const getPosts = async() = > {const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts/1')
setPosts(data)
}
return [posts, setPosts]
}
const App = () = > {
const [posts] = usePosts()
return (
<div>
<div>{posts.title}</div>
<div>{posts.body}</div>
</div>
);
}
export default App;
Copy the code