Mark As Completed Discussion

React Hooks

React Hooks are a feature introduced in React 16.8. They provide a way to use state and other React features in functional components, without the need for class components and lifecycle methods.

useState

The useState hook allows us to add state to functional components. It returns an array with two elements: the current state value and a function to update the state. Here's an example:

JAVASCRIPT
1const [count, setCount] = useState(0);

In this example, we're using the useState hook to add a count state to our component. The initial value of count is 0, and the setCount function is used to update the state value.

useEffect

The useEffect hook allows us to perform side effects in functional components. It's similar to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods of class components.

The useEffect hook takes two arguments: a callback function that performs the side effect and an optional array of dependencies. The callback function is executed after the component renders, and it can return a cleanup function that will be called when the component unmounts.

Here's an example of using the useEffect hook:

JAVASCRIPT
1useEffect(() => {
2  // This function is called after every render
3  console.log('Component mounted');
4
5  // Return a cleanup function
6  return () => {
7    console.log('Component unmounted');
8  };
9}, []);

In this example, the useEffect hook is used to log a message when the component mounts and unmounts. The empty array [] as the second argument ensures that the effect only runs once, similar to componentDidMount.

React Hooks provide a more concise and flexible way to work with state and side effects in functional components. They have become the recommended approach for writing React components.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment