DEV Community

Cover image for React Hooks Explained
Sanjay Singh Rajpoot
Sanjay Singh Rajpoot

Posted on

React Hooks Explained

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. You can just important them from a luray define them in a class and you are good to go. Hooks are backward-compatible, which means it does not contain any breaking changes. Also, it does not replace your knowledge of React concepts.

Few Rules that React hooks follow

Hooks are similar to JavaScript functions, but you need to follow these two rules when using them. Hooks rule ensures that all the stateful logic in a component is visible in its source code. These rules are:

  1. Only call Hooks at the top level
    Do not call Hooks inside loops, conditions, or nested functions. Hooks should always be used at the top level of the React functions. This rule ensures that Hooks are called in the same order each time a components renders.

  2. Only call Hooks from React functions
    You cannot call Hooks from regular JavaScript functions. Instead, you can call Hooks from React function components. Hooks can also be called from custom Hooks.

🔥 useState :
It is the most important and often used hook. The purpose of this hook to handle reactive data, any data that changes in the application is called state, when any of the data changes, React re-renders the UI.

const [count, setCount] = React.useState(0);
Enter fullscreen mode Exit fullscreen mode

🔥 useEffect :
It allows us to implement all of the lifecycle hooks from within a single function API.

// this will run when the component mounts and anytime the stateful data changes
React.useEffect(() => {
    alert('Hey, Nads here!');
});

// this will run, when the component is first initialized
React.useEffect(() => {
    alert('Hey, Nads here!');
}, []);

// this will run only when count state changes
React.useEffect(() => {
    fetch('nads').then(() => setLoaded(true));
}, [count]);

// this will run when the component is destroyed or before the component is removed from UI.
React.useEffect(() => {
    alert('Hey, Nads here');

    return () => alert('Goodbye Component');
});
Enter fullscreen mode Exit fullscreen mode

🔥 useContext :
This hook allows us to work with React's Context API, which itself a mechanism to allow us to share data within it's component tree without passing through props. It basically removes prop-drilling

const ans = {
    right: '✅',
    wrong: '❌'
}

const AnsContext = createContext(ans);

function Exam(props) {
    return (
        // Any child component inside this component can access the value which is sent.
        <AnsContext.Provider value={ans.right}>
            <RightAns />
        </AnsContext.Provider>
    )
}

function RightAns() {
    // it consumes value from the nearest parent provider.
    const ans = React.useContext(AnsContext);
    return <p>{ans}</p>
    // previously we were required to wrap up inside the AnsContext.Consumer
    // but this useContext hook, get rids that.
}
Enter fullscreen mode Exit fullscreen mode

🔥 useRef :
This hook allows us to create a mutable object. It is used, when the value keeps changes like in the case of useState hook, but the difference is, it doesn't trigger a re-render when the value changes.

The common use case of this, is to grab HTML elements from the DOM.

function App() {
    const myBtn = React.useRef(null);
    const handleBtn = () => myBtn.current.click();
    return (
        <button ref={myBtn} onChange={handleBtn} >
        </button>
    )
}
Enter fullscreen mode Exit fullscreen mode

Phew, that was fast! If some things didn’t quite make sense or you’d like to learn more in detail, you can read the React State Hook documentation.

Top comments (0)