Some examples of how to use React Hooks (specifically state and effect). Full React Hooks docs here
This allows you to maintain state and do 'stateful things' while writing functional as opposed to class based components. Functional components are preferable as React is optimised for functional components
yarn install
yarn start
The project runs on port 3000
This project has 4 components (App, App1, App2, App3)
To see the different behaviors change which component is used in index.js
Class based component using state. How to do state without React hooks.
Functional component using the State React hook. This is a rewrite of App.js
Class based component using state and componentDidMount
. This example also works for componentDidUpdate
and componentWillUnmount
Functional component using the Effect React hook. This is a rewrite of App3.js
.
useEffect
takes 2 params. This function is the equivalent of componentDidMount
. The function passed will run when the component mounts.
useEffect(() => {
setCount(getRandomInt(2, 100));
}, []);
Modifications include:
- Removing the square brackets. This will trigger the function passed as the first param on every re-render
useEffect(() => {
setCount(getRandomInt(2, 100));
});
- Specifying a specific state property. This will only call the function passed when count changes
useEffect(() => {
setCount(getRandomInt(2, 100));
}, [count]);
- The function returns a function. This function will be called when the component is destroyed (
componentWillUnmount
)
useEffect(() => {
setCount(getRandomInt(2, 100));
return () => console.log('end')
}, []);
A hook is just a function so it is possible to define your own
This project was bootstrapped with Create React App.