React Hook Interview Questions

What are hooks in React?

Hooks are a new feature added in React v16.8. Hooks allow you to use all the features of React without writing class components. For example, prior to version 16.8, we need a class component to manage the state of a component. We can now save state in the functional component using the useState hook .





Will React hooks work inside class components?

No.





Why were hooks introduced in React?

One of the reasons for introducing hooks was the difficulty of working with the this keyword inside class components. If not handled properly, this will have a slightly different meaning. This will break strings like this.setState () and other event handlers. By using hooks, we avoid this complexity when working with functional components.





Class components don't minify very well and also make hot reloading unreliable. This is another reason for creating hooks.





Another reason is that there is no specific way to reuse the logic of a stateful bean. Although HOC (Higher-Order Component) and Render Props templates (a method of passing props from parent to child using a function or closure) solve this problem, the code of the class component needs to be changed here. Hooks allow you to share stateful logic without changing the component hierarchy.





, . , (fetch) componentDidMount() componentDidUpdate(). : componentDidMount() componentWillUnmount() . .





useState? ?

useState - , . 2 . - . - .





useState React





import React, {useState} from "react";
      
      



useState, :





const [currentStateValue, functionToUpdateState] = useState(initialStateValue);
      
      



useState

. , , .





class Counter extends Component {
    state = {
        count: 0,
    };

    incrementCount = () => {
        this.setState({
            count: this.state.count + 1,
        });
    };

    render() {
        return (
            <div>
            <button onClick={this.incrementCount}>Count: {this.state.count}</button>
        </div>
    	);
    }
}
      
      



, React.









import React, { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);

    return (
        <div>
            <button
                onClick={() => {
                    setCount(count + 1);
                }}
            >
                Count: {count}
            </button>
        </div>
    );
}
      
      



useState 2

. .





class Counter extends Component {
    state = { count: 0 };

    incrementCount = () => {
        this.setState((prevState) => {
            return {
                count: prevState.count + 1,
            };
        });
    };

    decrementCount = () => {
        this.setState((prevState) => {
            return {
                count: prevState.count - 1,
            };
        });
    };

    render() {
        return (
            <div>
                <strong>Count: {this.state.count}</strong>
                <button onClick={this.incrementCount}>Increment</button>
                <button onClick={this.decrementCount}>Decrement</button>
            </div>
        );
    }
}
      
      



, React.





.





, callback. callback- .





import React, { useState } from "react";

function Counter() {
    const [count, setCount] = useState(0);

    const incrementCount = () => {
        setCount((prevCount) => {
            return prevCount + 1;
        });
    };

    const decrementCount = () => {
        setCount((prevCount) => {
            return prevCount - 1;
        });
    };

    return (
        <div>
            <strong>Count: {count}</strong>
            <button onClick={incrementCount}>Increment</button>
            <button onClick={decrementCount}>Decrement</button>
        </div>
    );
}
      
      



useState 3

, , .





export class Profile extends Component {
    state = {
        name: "Backbencher",
        age: 23,
    };

    onNameChange = (e) => {
        this.setState({
            name: e.target.value,
        });
    };

    onAgeChange = (e) => {
        this.setState({
            age: e.target.value,
        });
    };

    render() {
        return (
            <div>
                <form>
                    <input
                        type="text"
                        value={this.state.name}
                        onChange={this.onNameChange}
                    />
                    <input
                        type="number"
                        value={this.state.age}
                        onChange={this.onAgeChange}
                    />
                    <h2>
                        Name: {this.state.name}, Age: {this.state.age}
                    </h2>
                </form>
            </div>
        );
    }
}
      
      



, React.









import React, { useState } from "react";

function Profile() {
    const [profile, setProfile] = useState({
        name: "Backbencher",
        age: 23,
    });

    const onNameChange = (e) => {
        setProfile({ ...profile, name: e.target.value });
    };

    const onAgeChange = (e) => {
        setProfile({ ...profile, age: e.target.value });
    };

    return (
        <div>
            <form>
                <input type="text" value={profile.name} onChange={onNameChange} />
                <input type="text" value={profile.age} onChange={onAgeChange} />
                <h2>
                    Name: {profile.name}, Age: {profile.age}
                </h2>
            </form>
        </div>
    );
}
      
      



useState() , . setState() .





spread JavaScript.





?

setState() . , , , , , .





, setState() . useState() spread .





useEffect?

useEffect . . .





useEffect

, Boom , .





export class Banner extends Component {
    state = {
        count: 0,
    };

    updateState = () => {
        this.setState({
            count: this.state.count + 1,
        });
    };

    componentDidMount() {
        console.log("Boom");
    }

    componentDidUpdate() {
        console.log("Boom");
    }

    render() {
        return (
            <div>
                <button onClick={this.updateState}>State: {this.state.count}</button>
            </div>
        );
    }
}
      
      



console.log React.





.





componentDidMount() componentDidUpdate() - . useEffect. useEffect - , callback. callback , .





:





import React, { useState, useEffect } from "react";

function Banner() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        console.log("Boom");
    });

    const updateState = () => {
        setCount(count + 1);
    };

    return (
        <div>
            <button onClick={updateState}>State: {count}</button>
        </div>
    );
}
      
      



useEffect 2

:





function Banner() {
    const [count, setCount] = useState(0);
    const [name, setName] = useState("");

    useEffect(() => {
        console.log(" ");
    });

    return (
        <div>
            <button onClick={() => setCount(count + 1)}>State: {count}</button>
            <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
            />
        </div>
    );
}
      
      



ยซ ยป . ?





.





useEffect , . props , . , , , . count .





useEffect:





useEffect(() => {
    console.log("Count is updated");
}, [count]);
      
      



useEffect 3

, . componentDidMount() .





export class Clock extends Component {
    state = {
        date: new Date(),
    };

    componentDidMount() {
        setInterval(() => {
            this.setState({
                date: new Date(),
            });
        }, 1000);
    }

    render() {
        return <div>{this.state.date.toString()}</div>;
    }
}
      
      



React.





.





componentDidMount() - , . useEffect, componentDidMount(). useEffect props . , - useState. . , React props, . , useEffect , componentDidMount().





React.





function Clock() {
    const [date, setDate] = useState(new Date());

    useEffect(() => {
        setInterval(() => {
            setDate(new Date());
        }, 1000);
    }, []);

    return <div>{date.toString()}</div>;
}
      
      



useEffect 4

, .





componentDidMount() {
    window.addEventListener("mousemove", this.handleMousePosition);
}

componentWillUnmount() {
    window.removeEventListener("mousemove", this.handleMousePosition);
}
      
      



Rewrite this code in the style of React hooks.





Decision.





To use the functionality of the componentWillUnmount () lifecycle method in the useEffect hook, you need to return a callback with the code that needs to be executed when the component is unmounted.





useEffect(() => {
    window.addEventListener("mousemove", handleMousePosition);

    return () => {
        window.removeEventListener("mousemove", handleMousePosition);
    }
}, []);
      
      



The useContext task

Here is a code snippet from the Context.Consumer component.





import { NameContext, AgeContext } from "./ProviderComponent";

export class ConsumerComponent extends Component {
    render() {
        return (
            <NameContext.Consumer>
                {(name) => {
                    return (
                        <AgeContext.Consumer>
                            {(age) => (
                                <div>
                                    Name: {name}, Age: {age}
                                </div>
                            )}
                        </AgeContext.Consumer>
                    );
                }}
            </NameContext.Consumer>
        );
    }
}
      
      



Rewrite the ConsumerComponent  using the useContext hook  .





Solution .





Hooks can only be used in a functional component.





ConsumerComponent can be rewritten like this:





function ConsumerComponent() {
    const name = useContext(NameContext);
    const age = useContext(AgeContext);

    return (
        <div>
            Name: {name}, Age: {age}
        </div>
    );
}
      
      










All Articles