Before diving into this blog, make sure you've checked out the previous blogs in this series on my profile: ReactJS Beginner to Advanced Series
These blogs will provide you with essential knowledge and context for understanding the concepts discussed here. Once you're caught up, let's explore Hooks in React!
What are React Hooks?
- Hooks are functions that let you use state and other React features without writing a class. They are introduced in React 16.8. Before hooks, you had to use a class component to use features like state, lifecycle methods, and context. With hooks, you can use these features without writing a class.
Why Hooks?
- Simplicity: Hooks simplify the code and make it easier to understand compared to class components.
- Reusability: Hooks allow you to reuse stateful logic across multiple components without changing the component hierarchy.
- Better Performance: Hooks can optimize the performance of functional components by avoiding unnecessary re-renders.
There are many different hooks available, but the most common ones are:
- useState: This hook lets you add state to a function component.
- useEffect: This hook lets you run side effects in a function component.
- useContext: This hook lets you access context from a function component.
- useReducer: This hook lets you manage state with a reducer.
- useRef: This hook lets you get a reference to a DOM element.
- useMemo: This hook lets you memoize a value.
- useCallback: This hook lets you memoize a callback function.
UseState:
- The useState hook allows you to add state to functional component. It returns an array with two values: the current state and a function to update it.
- If you have data that needs to be stored and modified within a component, such as form input values, toggles for showing/hiding content, or tracking user interactions within a component then you should use useState hook.
- In below example, useState is a hook that adds state to the Counter functional component. It returns a stateful value (count) and a function (setCount) to update it.
useEffect:
- The useEffect hook allows you to run side effects, such as fetching data or updating the DOM, in a functional component. It takes a callback function as its first argument, which is called after the component has rendered.
- The useEffect hook is used to run an async function featchData that Featches data from an API and updates the component's state with the result. The empty array [] passed as the second argument to useEffect means that the effect will only run once, when the compoent is first rendered.
useContext:
What is useContext?
- Imagine you have some data or functions that multiple components in your React app need to access. Instead of passing this data down through each component using props, you can create a context to make this data available to all components within a certain part of your app.
When to Use useContext?
- Use useContext when you have data or functions that are needed by multiple components and you want to avoid prop drilling (passing props through many layers of components).
Simple Use Case: Multi-Language App
Let's say you're building a multi-language app. You have a context called LanguageContext
which holds the current language selected by the user and a function to change the language.
//LanguageContext.js:
import React, { createContext, useState } from 'react';
const LanguageContext = createContext();
const LanguageProvider = ({ children }) => {
const [language, setLanguage] = useState('en');
const changeLanguage = (newLanguage) => {
setLanguage(newLanguage);
};
return (
<LanguageContext.Provider value={{ language, changeLanguage }}>
{children}
</LanguageContext.Provider>
);
};
export { LanguageProvider, LanguageContext };
//main.jsx
import React from 'react';
import { LanguageProvider } from './LanguageContext';
import App from './App';
const MainApp = () => {
return (
<LanguageProvider>
<App />
</LanguageProvider>
);
};
export default MainApp;
//header.jsx
import React, { useContext } from 'react';
import { LanguageContext } from './LanguageContext';
const Header = () => {
const { language, changeLanguage } = useContext(LanguageContext);
return (
<header>
<h1>{language === 'en' ? 'Hello' : 'Hola'}</h1>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('es')}>Spanish</button>
</header>
);
};
export default Header;
More to Go
Thank you for reading this blog, now rest of the hooks we contains in next blog session. Stay tuned for more insightful content!