React useState and useEffect
Neil Haddley • February 8, 2021
Create a React app using the useState and useEffect hook.
React Hooks
I used React Hooks to manage state and side effects in React function components. The key hooks I used were:
useState — manages component state, useful for tracking values like checked/unchecked or data fetched from an API.
useEffect — replaces componentDidMount, componentDidUpdate, and componentWillUnmount. I used it to fetch data before rendering.
useContext — makes global state accessible to any component without passing props down manually.
useReducer — preferable to useState for complex state logic; provides an alternative to Redux.
Fetching data from an API
I used useState and useEffect to call an API from a React functional component.
useState and useEffect
JAVASCRIPT
1const [data, setData] = useState(); 2 3 useEffect(() => { 4 axios 5 .get("/books") 6 .then(result => { 7 setData(() => result.data) 8 }) 9 .catch(err => { 10 console.log(err) 11 }) 12 })