DEV Community

AKSH DESAI
AKSH DESAI

Posted on

useCallback() hook - Web dev Simplified

Part 1

Folder Structure

Folder Image

App.js Code

import { useState, useCallback } from "react";
import Todos from "./Todos";

const App = () => {
    const [count, setCount] = useState(0);
    const [todos, setTodos] = useState([]);

    const increment = () => {
        setCount((c) => c + 1);
    };

    // const addTodo = () => {
    //     console.log('inside function');
    //     setTodos((t) => [...t, "New Todo"]);
    // };

    const addTodo = useCallback(() => {
        console.log('inside function');
        setTodos((t) => [...t, "New Todo"]);
    }, [todos]);

    console.log('parent render');
    return (
        <>
            <Todos todos={todos} addTodo={addTodo} />
            <hr />
            <div>
                Count: {count}
                <button onClick={increment}>+</button>
            </div>
        </>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Todos.js Code

import { memo } from "react";

const Todos = ({ todos, addTodo }) => {
  console.log("child render");
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
      <button onClick={addTodo}>Add Todo</button>
    </>
  );
};

export default memo(Todos);
Enter fullscreen mode Exit fullscreen mode

Output

Output Image

Output Image

Part 2

Folder Structure

Folder Structure

App.js Code

import { useState, useCallback } from 'react'
import List from './List';


export default function App() {

    const [number, setNumber] = useState(1);
    const [dark, setDark] = useState(true);

    const getItems = useCallback(() => {
        return [number, number + 1, number + 2];
    }, [number]);

    const theme = {
        backgroundColor: dark ? "grey" : "white",
        color: dark ? "white" : "grey"
    };

    return (
        <div style={theme}>
            <input type='number' value={number} onChange={(e) => setNumber(e.target.value)} /> <br />
            <button onClick={() => setDark(prevDark => !prevDark)}> Toggle Theme </button>

            <List getItems={getItems} />
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

List.js Code

import { useState, useEffect, memo } from 'react'

const List = ({ getItems }) => {

    const [items, setItems] = useState([]);

    useEffect(() => {
        setItems(getItems());
        console.log('updating items');
    }, [getItems]);

    console.log('in children', getItems());

    return items.map(item => <div key={item}> {item} </div>)
};

export default memo(List);
Enter fullscreen mode Exit fullscreen mode

Output
Folder Structure

Thank You.
You can follow us on:
Youtube
Instagram

Top comments (0)